Thuta Learning
C
IntermediateProgrammingBeginner

Function Declaration

CLesson 2025 min

What you'll walk away with

  • Tell a declaration (prototype) from a definition and list what a prototype must contain
  • Explain and fix the "implicit declaration of function" error
  • Explain the difference between int f(void); and int f(); in C17
  • Put prototypes in a header file with an include guard and keep private helpers static

Explain it simply

Explain it simply

The C compiler reads a file once, from top to bottom. When it meets add(5, 3) inside main() and the code for add is still further down, it has no idea yet what that function looks like.

A prototype works like a book's table of contents. The single line int add(int a, int b); tells the compiler in advance: "a function called add exists, takes two ints and returns an int, and its details come later". After that, you can arrange your functions in whatever order reads best.

Problem → Why → Solution

The problem: putting main() first breaks the build

It is natural to put main() at the top so a reader sees the big picture first, with the helpers below. Compile the code below with GCC 16, though, and you get two errors. Under old C rules the compiler guessed that an unknown function returns int and carried on, so the second error says the real definition returning double conflicts with that guess.

average_bug.c
#include <stdio.h>

int main(void) {
    double avg = average(7, 8);   /* error: implicit declaration */
    printf("%.1f\n", avg);
    return 0;
}

double average(int a, int b) {    /* error: conflicting types */
    return (a + b) / 2.0;
}

Why is the compiler this strict?

To generate a call, the compiler must know the return type and the parameter types, so it can convert the arguments and read the result from the right place. Older compilers guessed int and only warned, which made functions returning double produce meaningless numbers. GCC 14 and newer treat it as an error for C99 and later standards.

Core concept: a declaration promises, a definition delivers

A declaration (prototype) holds the return type, the name and the parameter type list, and ends with a semicolon instead of a body. A definition repeats that header and adds the { } body that does the work. Each function has exactly one definition in the whole program, but it may be declared any number of times as long as every declaration agrees.

Once it has seen a prototype, the compiler checks the argument count at every call, converts each argument to its parameter type and knows what type the result has. Without a prototype none of these checks can happen, because the compiler has nothing to compare the call against. Parameter names in a prototype are ignored by the compiler, yet int clamp(int value, int low, int high); documents the call far better than int clamp(int, int, int);.

In C17, a function without parameters is declared int menu(void);. Writing int menu(); with empty parentheses means "parameters unknown", so a call like menu(1, 2, 3) is not checked at all. C23 makes () mean the same as (void), but (void) is unambiguous in both standards.

As a project grows, each .c file is compiled separately and the linker connects calls to definitions. A .c file together with everything it includes is called a translation unit, and the compiler only ever sees one translation unit at a time. So the prototypes other files may call go into a header (.h) file, included both by the files that call the functions and by the file that defines them, which lets the compiler catch a prototype that disagrees with its definition. Helpers that should stay private to one file are marked static and kept out of the header.

Mental model: the compiler's single pass
  1. The compiler reads top to bottom once
  2. A prototype records the signature
  3. Each call is checked against it
  4. The linker joins calls to definitions

A missing prototype fails at compile time; a missing definition fails at link time.

General pattern

c
ReturnType name(Type1 param1, Type2 param2);   /* declaration */
ReturnType other(void);                       /* takes no arguments */

int main(void) {
    /* calls to name() and other() are checked here */
}

ReturnType name(Type1 param1, Type2 param2) {  /* definition */
    /* body */
}

The prototype ends with a semicolon and must match the definition's header type for type. Declare functions that take no arguments with (void). The definition can then live anywhere in the file.

Example: a prototype above main(), the definition below

Here add() is called inside main() while its definition sits at the very bottom of the file. The one-line prototype at the top is what lets the compiler check the call. Comment the prototype out and recompile to see the implicit declaration error for yourself.

c
#include <stdio.h>

// Function declaration
int add(int a, int b);

int main() {
  int result = add(5, 3);
  printf("Result: %d", result);
  return 0;
}

// Function definition
int add(int a, int b) {
  return a + b;
}

Code breakdown

  1. Prototypeint add(int a, int b);

    A declaration with no body, ending in a semicolon. From this line on, add() can be called anywhere in the file.

  2. main()int main() {

    In a definition, () means no parameters, so this works. In C17, int main(void) is still better because it is a full prototype, and -Wstrict-prototypes warns about the () form.

  3. Checked callint result = add(5, 3);

    Because of the prototype, the compiler checks that there are two int arguments. add(5) would be rejected with "too few arguments".

  4. Outputprintf("Result: %d", result);

    Prints Result: 8. There is no \n, so your terminal prompt may appear on the same line; in your own programs, end the line with \n.

  5. Definitionint add(int a, int b) {

    The return type, parameter types and their order must match the prototype exactly. Changing it to double add(...) triggers "conflicting types for 'add'".

You should see
Result: 8

Multi-file programs: the header file

When a program grows, related functions move into their own .c file and the prototypes other files may use go into a matching .h file. The three lines #ifndef / #define / #endif form an include guard, so even if the header is included twice, its contents are only processed once.

temperature.h
#ifndef TEMPERATURE_H
#define TEMPERATURE_H

double c_to_f(double celsius);
int is_freezing(double celsius);

#endif
temperature.c
#include "temperature.h"   /* lets the compiler compare prototypes */

static double scale(double value) {   /* private to this file */
    return value * 9.0 / 5.0;
}

double c_to_f(double celsius) {
    return scale(celsius) + 32.0;
}

int is_freezing(double celsius) {
    return celsius <= 0.0;
}
main.c
#include <stdio.h>
#include "temperature.h"

int main(void) {
    double today = -3.5;
    printf("%.1f C = %.1f F\n", today, c_to_f(today));
    printf("freezing: %s\n", is_freezing(today) ? "yes" : "no");
    return 0;
}

To build, give the compiler both .c files; the header is pulled in by #include and never appears on the command line. The program prints "-3.5 C = 25.7 F" and "freezing: yes".

bash
gcc -std=c17 -Wall -Wextra main.c temperature.c -o temperature
./temperature

In real projects

Where this shows up in real projects

Every #include <stdio.h> brings in prototypes for printf, fopen and friends. Their definitions already sit compiled inside the C library, and the linker connects your calls to them. Libraries such as SQLite and zlib work the same way: a header like sqlite3.h is the public API, and the implementation stays hidden behind it.

On team projects, a header is treated as a module's contract. Change a prototype in it and every file that includes the header is recompiled, with the compiler pointing at each call that no longer fits. Build tools such as make and CMake track header changes and rebuild only the files affected. When you hit a linker error like "undefined reference to", the usual cause is a prototype that exists while the .c file holding its definition was left out of the build.

Common mistakes

Common mistakes

1. A prototype that disagrees with its definition

Declaring double average(int a, int b); and defining double average(double a, double b) makes GCC stop with "conflicting types for 'average'". The more dangerous case is a prototype in a header that the defining .c file never includes: the compiler cannot compare them, and the program may silently compute wrong values. Always include your own header in its .c file.

2. Declaring with empty parentheses in C17

In C17, int area(); is not a prototype. gcc -std=c17 -Wall -Wextra compiles both area(2, 3, 4) and area(2) without a single warning. Calling with the wrong number of arguments is undefined behaviour, and area(2) multiplies by whatever garbage happens to sit where h should be. Write int area(int w, int h); with full types; -Wstrict-prototypes reports "function declaration isn't a prototype" for the empty form.

3. Putting a function definition in a header

Write int twice(int x) { return 2 * x; } in a header included by two .c files and each file gets its own definition, so the linker fails with "multiple definition of `twice'". An include guard only stops repeats within one file, so it cannot help here. Keep only the prototype in the header and the body in exactly one .c file.

4. A prototype whose definition is never built

A prototype satisfies the compiler but does not create the function. Build with only gcc main.c, forgetting temperature.c, and the linker reports "undefined reference to `c_to_f'".

Best practices

Best practices

  • Declare parameterless functions with (void) and turn on -Wstrict-prototypes.
  • Give prototype parameters meaningful names; they are free documentation.
  • Pair each module's .h with its .c, and include the module's own header first in the .c file.
  • Make helpers that other files must not call static and leave them out of the header.

Mini challenge

Mini challenge: a receipt with main() first

Write a program that prints a small shop receipt, with main() placed below the prototypes and above all the definitions.

  • double line_total(int quantity, double unit_price) multiplies quantity by price
  • double apply_discount(double amount, int percent) takes percent off the amount
  • void print_line(const char *item, int quantity, double unit_price) prints one receipt line
  • All three prototypes go above main(), all three definitions below it, with no warnings under -Wstrict-prototypes
receipt.c
#include <stdio.h>

/* TODO: prototypes for line_total, apply_discount and print_line */

int main(void) {
    // TODO: print a line for 2 Notebooks at 1.50 and 5 Pens at 0.50
    // TODO: compute the subtotal with line_total()
    // TODO: print the subtotal and the total after a 10% discount
    return 0;
}

/* TODO: definitions, matching the prototypes exactly */

Expected: The program prints: Notebook x2 3.00 Pen x5 2.50 subtotal: 5.50 after 10% discount: 4.95

Show hint

The easiest way to write a prototype is to copy the definition's first line and replace the { with ;. To print a literal % sign with printf, write %%.

Show solution
receipt.c
#include <stdio.h>

/* Prototypes: the compiler reads these before main() */
double line_total(int quantity, double unit_price);
double apply_discount(double amount, int percent);
void print_line(const char *item, int quantity, double unit_price);

int main(void) {
    print_line("Notebook", 2, 1.50);
    print_line("Pen", 5, 0.50);

    double subtotal = line_total(2, 1.50) + line_total(5, 0.50);
    printf("subtotal: %.2f\n", subtotal);
    printf("after 10%% discount: %.2f\n", apply_discount(subtotal, 10));
    return 0;
}

/* Definitions: same return types and parameter types as above */
double line_total(int quantity, double unit_price) {
    return quantity * unit_price;
}

double apply_discount(double amount, int percent) {
    return amount * (100 - percent) / 100.0;
}

void print_line(const char *item, int quantity, double unit_price) {
    printf("%-9s x%d %6.2f\n", item, quantity, line_total(quantity, unit_price));
}

Quick quiz 1 / 3

main() calls average(7, 8), the definition of average comes after main(), and there is no prototype. What does gcc -std=c17 (GCC 16) do?

Quick quiz 2 / 3

In C17, with int area(); declared, what does gcc -std=c17 -Wall -Wextra report for the call area(2, 3, 4)?

Quick quiz 3 / 3

Your build fails with "undefined reference to `add'". What is the most likely cause?

What to remember

  • The compiler reads a file top to bottom once, so a function must be declared or defined before it is called.
  • A prototype gives the return type, name and parameter types, and must match the definition exactly.
  • In C17, write (void) for no parameters; () switches argument checking off.
  • Keep prototypes in a header with an include guard and each definition in exactly one .c file.

GNU C compiler diagnostics — GNU Project

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.