#Forward declarations in c

12 messages · Page 1 of 1 (latest)

marble mantle
#

Say I have a main.c file and a add.c file, and I include add.c in main.c as so :

main.c

#include <stdio.h>

#include "add.c"

int add(int a, int b);

int main(int argc, char const *argv[])
{
    printf("%d", add(1, 2));
    
    return 0;
}

add.c

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

do I actually need to forward declare int add(int a, int b) before calling the function add() ? Because without declaring it first it still compiles without an issue and that's bugging me a bit, maybe I am mistaking the way c works with c++ ?

tender mirageBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

leaden solstice
#

If the function implementation happens before the main you don't need to declare it.
If the function implementation happens after the main you do need to declare it.
Reason is that by declaring it you tell the compiler that there does exist a function add(int, int) even if there is no implementation compiled for it yet, so when it tries to parse the main method's implementation it is able to link the add(int, int) method called in your main to an existing function. For the sake of this just imagine the declaration to be a pointer towards a function, and by declaring it you basically allocate some memory, so that when the compiler tries to check if such a function exists it finds that it links to actual memory.

Example:
You do need to declare it:

int add(int, int);

int main() {
    int x = add(1, 2);
}

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

You don't need to declare it:

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

int main() {
    int x = add(1, 2);
}
severe thicket
#

Don't #include C files

marble mantle
#

sorry but I am a bit confused, how do you work with multiple files if you don't include them, I might have missed something here

severe thicket
#

You compile .c files separately and link the resulting object files

#

#include is for header files (.h)

#

Header files contain forward declarations

leaden solstice
#

a.c

extern int add(int, int);

int main() {
    add(1, 2);
}

b.c

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

Compile:

gcc a.c b.c -o o
marble mantle
#

Alright I think I understand, but I think I need a bit more reading on the subject, thanks a lot for those clear answers !

tender mirageBOT
#

@marble mantle Has your question been resolved? If so, run !solved :)

marble mantle
#

!solved