在我的项目中,我有两个库和一个程序。
Lib1.c
和Lib1.h
是第一个库(Lib1.so
)的两个文件。Lib2.c
和Lib2.h
是第二个库(Lib2.so
)的两个文件。prog.c
是程序(prog
)的主文件。程序(prog
)仅链接到第二个库(Lib2.so
),第二个库(Lib2.so
)链接到第一个库(Lib1.so
)。
在Lib1.c
中,我声明了全局变量(int var = 0;
),在Lib1.h
中,我声明了(extern int var;
)。
在Lib2.h
中,我有一个声明(extern int var;
),以便在主程序中使用var
变量。
在main()
函数中,我将Lib2.h
包含在prog.c
文件中,并且有一个声明(var = 5;
)
Lib1.c:
#include <stdio.h>
#include "Lib1.h"
int var = 0;
int funct(void)
{
printf("hello world \n");
return 0;
}
Lib1.h:
extern int var;
int funct(void);
Lib2.c:
#include <stdio.h>
#include "Lib2.h"
int funct2(void)
{
printf("Library 2 \n");
funct();
return 0;
}
Lib2.h:
#include "Lib1.h"
extern int var;
int funct2(void);
prog.c:
#include <stdio.h>
#include "Lib2.h"
int main()
{
var = 5;
printf("===>var=%d\n", var);
funct2();
return 1;
}
命令:
gcc -c -Wall -Werror -fpic Lib1.c
gcc -shared -o Lib1.so Lib1.o
gcc -c -Wall -Werror -fpic Lib2.c
gcc -shared -o Lib2.so Lib2.o -ldl /home/test/Lib1.so
gcc prog.c -o prog -ldl /home/test/Lib2.so
[当我尝试编译程序(prog.c
)时,在链接步骤中出现如下错误。
/usr/bin/ld: /tmp/ccKaq16a.o: undefined reference to symbol 'var'
/home/test/Lib1.so: error adding symbols: DSO missing from command line
在第一个库中定义主函数时,是否可以在主函数中使用var变量?
您将程序链接到Lib2,而不链接到Lib1。您还需要添加它。创建Lib2时,您也不需要显式链接Lib1
gcc -c -Wall -Werror -fpic Lib1.c
gcc -shared -o Lib1.so Lib1.o
gcc -c -Wall -Werror -fpic Lib2.c
gcc -shared -o Lib2.so Lib2.o
gcc prog.c -o prog /home/test/Lib2.so /home/test/Lib1.so