c - 如何在C中调用动态库?

标签 c linux gcc dll

操作系统:Ubuntu 14.04 (值得信赖的塔尔)

编写两个 .c 文件,分别命名为 dtest1.cdtest2.c

文件dtest1.c

int p = 2;

void print()
{
    printf("this is the first DLL test!\n");
}

文件dtest2.c

int p = 3;

void print()
{
    printf("this is the second DLL test!\n");
}

然后,编译它们得到两个名为dtest1.sodtest2.so的文件:

gcc -O -fpic -shared -o dtest1.so dtest1.c
gcc -O -fpic -shared -o dtest2.so dtest2.c

编写一个名为dtest3.c的.c文件。

文件dtest3.c

#include "dtest1.so"

int main ()
{
    print();
    return 0;
}

到目前为止,一切都很好。没有任何错误(只有警告)。

然后:

gcc -o dtest3 dtest3.c dtest1.so

错误:

In file included from dtest3.c:1:0:
dtest1.so:17:1: warning: null character(s) ignored [enabled by default]
dtest1.so:17:2: error: stray ‘\260’ in program
   ......
   ......    /*omit too many similar information */
dtest1.so:18:2: error: stray ‘\212’ in program
dtest1.so:18:2: error: stray ‘\1’ in program
In file included from dtest3.c:1:0:
dtest1.so:18:956: warning: null character(s) ignored [enabled by default]
In file included from dtest3.c:1:0:
dtest1.so:18:2: error: stray ‘\244’ in program
dtest1.so:18:2: error: stray ‘\1’ in program
In file included from dtest3.c:1:0:
dtest1.so:18:980: warning: null character(s) ignored [enabled by default]
dtest1.so:18:982: warning: null character(s) preserved in literal [enabled by default]
dtest1.so:18:982: warning: missing terminating " character [enabled by default]
In file included from dtest3.c:1:0:
dtest1.so:18:2: error: missing terminating " character

这有什么问题吗?

最佳答案

库是编译后的代码,而不是(文本)源代码。 #include 只是插入给定文件的内容,因此它应该是源代码。您必须通过将库作为参数传递给链接器来链接库。

阅读here了解更多。

关于c - 如何在C中调用动态库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31907686/

相关文章:

c - 在 "C"头文件中声明的静态函数

c++ - 在C中永久存储数组

C中的恒定大小全局数组

linux - glibc 中这段代码段的目的是什么

windows - 如何使用 sys/ioctl.h 将代码移植到 MinGW gcc?

c++ - 模板 - 巨大的目标文件导致链接器崩溃

c++ - 使用 gcc 或 cpp 预处理 C 代码而不解析宏

c - 如何为需要多次输入的 C 程序编写 Bash 脚本?

linux - 如何在 Linux 中创建虚拟命令支持文件?

c - linux 使用系统 ("ping") 在守护进程中被阻止