Today I was trying to write a static link library using Clion and found this problem:
This is the code for the header file:
#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
This is the code for the c file:
#include "hello.h"
void say(int num) {
printf("%d\n", num);
}
After the
build, we get the.a static library
Create a new file and configure Cmake as follows:
< div class = "aw - list - img >
< br / > link header file with the static library
After
, write the following code in the c file:
#include "hello.h"
int main() {
say(c.a);
}
To my surprise, it made an error, as follows:
FAILED: t1.exe
cmd.exe /C "cd . & & E: \ CLION2-1.1 \ bin \ mingw \ bin \ GCC exe - g CMakeFiles/t1. Dir/main c.o bj - 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. "< br / > 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.
Then I try another scheme, using printf:
#include "hello.h"
int main() {
printf("%d", c.a);
}
No error is reported on this run, the correct number is printed
This is surprising to me. a member of structure c will get an error when used for say(), but not for printf(). It does the same thing, but the structure is defined inside the header file.
Here I am using clion's default configuration:
For answers, thanks

Read the full article
Fold