#ifndef DB_HELLO_H
#define DB_HELLO_H
#include "stdio.h"
typedef struct{
int a;
int b;
}ts;
ts c = {
.a = 6,
.b = 10
};
void say(int a);
#endif
#include "hello.h"
void say(int num) {
printf("%d\n", num);
}
#include "hello.h"
int main() {
say(c.a);
}
FAILED: t1.exe
cmd.exe /C "cd . && E:\CLION2~1.1\bin\mingw\bin\gcc.exe -g CMakeFiles/t1.dir/main.c.obj -o t1.exe -Wl,--out-implib,libt1.dll.a -Wl,--major-image-version,0,--minor-image-version,0 -LC:/Users/Administrator/CLionProjects/untitled -LG:/Cproject/lib -Wl,-Bstatic -ldb -Wl,-Bdynamic -lkernel32 -luser32 -lgdi32 -lwinspool -lshell32 -lole32 -loleaut32 -luuid -lcomdlg32 -ladvapi32 && cd ."
E:\CLion 2022.3.1\bin\mingw\bin/ld.exe: G:/Cproject/lib\libdb.a(hello.c.obj):C:/Users/Administrator/CLionProjects/db/hello.h:11: multiple definition of `c'; CMakeFiles/t1.dir/main.c.obj:G:/Cproject/include/hello.h:11: first defined here
collect2.exe: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.
#include "hello.h"
int main() {
printf("%d", c.a);
}
虽然你头文件加了宏,防止hello.h被重复包含(即你这里hello.c,main.c中都包含hello.h没关系),但是你无法防止你定义的变量c被重复包含,所以它报了重定义的错。
而当你改成printf后,不用hello.c中的say,相当于此时没有hello.c,而只有main.c执行只包含了一次hello.h,即你的变量c只被定义了一次,故没有重定义,所以不会再报错。