cmultiple-definition-error

How to prevent multiple definitions in C?


I'm a C newbie and I was just trying to write a console application with Code::Blocks. Here's the (simplified) code: main.c:

#include <stdio.h>
#include <stdlib.h>
#include "test.c" // include not necessary for error in Code::Blocks

int main()
{
    //t = test(); // calling of method also not necessary
    return 0;
}

test.c:

void test() {}

When I try to build this program, it gives the following errors:

*path*\test.c|1|multiple definition of `_ test'|
obj\Debug\main.o:*path*\test.c|1|first defined here|

There is no way that I'm multiply defining test (although I don't know where the underscore is coming from) and it seems highly unlikely that the definition is somehow included twice. This is all the code there is.

I've ruled out that this error is due to some naming conflict with other functions or files being called test or test.c. Note that the multiple and the first definition are on the same line in the same file.

Does anyone know what is causing this and what I can do about it? Thanks!


Solution

  • You actually compile the source code of test.c twice:

    What you need in your main.c in order to use the test() function is a simple declaration, not its definition. This is achieved by including a test.h header file which contains something like:

    void test(void);
    

    This informs the compiler that such a function with input parameters and return type exists. What this function does ( everything inside { and } ) is left in your test.c file.

    In main.c, replace #include "test.c" by #include "test.h".

    A last point: with your programs being more complex, you will be faced to situations when header files may be included several times. To prevent this, header sources are sometimes enclosed by specific macro definitions, like:

    #ifndef TEST_H_INCLUDED
    #define TEST_H_INCLUDED
    
    void test(void);
    
    #endif