今天我在尝试使用Clion写静态链接库的时候,发现了这样一个问题:
这个是头文件的代码:
#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
这个是c文件的代码:
#include "hello.h"
void say(int num) {
printf("%d\n", num);
}
构建之后得到了.a静态库
新建一个文件,配置Cmake文件如下:
链接头文件与静态库
之后在c文件里编写如下代码:
#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.
然后我又尝试另一种方案,使用printf:
#include "hello.h"
int main() {
printf("%d", c.a);
}