c - "Multiple definition", "first defined here" errors -
i have 3 projects: server, client , commons. making header & source pairs in commons doesn't cause problems , can access functions freely both server , client.
however, reason making additional source/header files within server or client project causes multiple definition of (...)
, first defined here
errors.
example:
commands.h (in root dir of client project)
#ifndef commands_h_ #define commands_h_ #include "commands.c" void f123(); #endif /* commands_h_ */
commands.c (in root dir of client project)
void f123(){ }
main.c (in root dir of client project)
#include "commands.h" int main(int argc, char** argv){ }
errors:
make: *** [client] error 1 client first defined here client multiple definition of `f123' commands.c
cleaning, rebuilding index, rebuilding projects doesn't help. neither restarting computer.
the problem here including commands.c
in commands.h
before function prototype. therefore, c pre-processor inserts content of commands.c
commands.h
before function prototype. commands.c
contains function definition. result, function definition ends before function declaration causing error.
the content of commands.h
after pre-processor phase looks this:
#ifndef commands_h_ #define commands_h_ // function definition void f123(){ } // function declaration void f123(); #endif /* commands_h_ */
this error because can't declare function after definition in c. if swapped #include "commands.c"
, function declaration error shouldn't happen because, now, function prototype comes before function declaration.
however, including .c
file bad practice , should avoided. better solution problem include commands.h
in commands.c
, link compiled version of command main file. example:
commands.h
ifndef commands_h_ #define commands_h_ void f123(); // function declaration #endif
commands.c
#include "commands.h" void f123(){} // function definition
Comments
Post a Comment