How to prevent multiple definitions in C?

后端 未结 7 1024
失恋的感觉
失恋的感觉 2020-12-08 00:36

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 
#incl         


        
7条回答
  •  时光说笑
    2020-12-08 01:12

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

    • The first time when compiling test.c itself,
    • The second time when compiling main.c which includes all the test.c source.

    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
    

提交回复
热议问题