How to prevent multiple definitions in C?

后端 未结 7 1026
失恋的感觉
失恋的感觉 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:14

    The underscore is put there by the compiler and used by the linker. The basic path is:

    main.c
    test.h ---> [compiler] ---> main.o --+
                                         |
    test.c ---> [compiler] ---> test.o --+--> [linker] ---> main.exe
    

    So, your main program should include the header file for the test module which should consist only of declarations, such as the function prototype:

    void test(void);
    

    This lets the compiler know that it exists when main.c is being compiled but the actual code is in test.c, then test.o.

    It's the linking phase that joins together the two modules.

    By including test.c into main.c, you're defining the test() function in main.o. Presumably, you're then linking main.o and test.o, both of which contain the function test().

    0 讨论(0)
提交回复
热议问题