Defining the same function in different C source filesIn general, to maintain the simplicity and efficiency of the program, it is not recommended to define the same function (with the same return type and parameter types) in different C source files. Otherwise, the compiler may throw an error indicating multiple definitions, as shown in the following code where the compiler will output:multiple definition of `test’Custom header file
//test.h#ifndef TEST_H#define TEST_Hint test();#endif
Defining test in different source files
//test1.c#include "test.h"#include <stdio.h>int test() { return 1;}int main() { int a = test(); printf("a = %d\n", a); return 0;}
//test2.c#include "test.h"int test(){ return 1;}
When compiling test1.c and test2.c together, the MinGW compiler will throw:multiple definition of `test’。If you must redefine it, what should you do?In the test.h header file, modify the declaration of the test() function to be static, for example:
static int test();
After that, recompiling test1.c and test2.c will not throw a duplicate definition error. This is because, after being declared static, the test() function is only visible in the current source file when the header file is included, thus avoiding multiple definitions.So, can we use static to modify the main function and define two or more main functions?No, we cannot. Let’s look at the following example:Header file:
#ifndef TEST_H#define TEST_Hstatic int main();#endif
test1.c:
#include "test.h"#include <stdio.h>int main() { return 0;}
test2.c:
#include "test.h"int main(){ return 0;}
When compiling multiple source files, the MinGW compiler throws:
undefined reference to `WinMain'
This means that the linker cannot find the main entry point of the program (the main function).It is evident that a C language program can have only one main function.Disclaimer: The content is for reference only and does not guarantee correctness; it should not be used as the basis for any decisions!