C语言 如何在 Linux 中链接和编译 .so 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19129939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:36:18  来源:igfitidea点击:

How to link and compile with .so file in Linux

cgcc

提问by Brainy

I am having .c and .so file. I tried by using the following compilation: gcc main.c -ldl. In that .c file i linked to .so file through dlsym(). How to compile using .so file with .c.

我有 .c 和 .so 文件。我尝试使用以下编译:gcc main.c -ldl. 在那个 .c 文件中,我通过 .so 文件链接到 .so 文件dlsym()。如何使用 .so 文件和 .c 进行编译。

回答by vkulkarni

Probably you can do this:

也许你可以这样做:

when linking do:

链接时执行:

g++ -o prog prog.o -ldllname

If libdllname.so is not in the system directory then add its directory to the library path:

如果 libdllname.so 不在系统目录中,则将其目录添加到库路径中:

g++ -o prog prog.o -L/path/to/my/library/folder -ldllname

回答by dexterous

This is based on your further comments. First guard the declarations of your header file.

这是基于您的进一步评论。首先保护头文件的声明。

#ifndef HEADER_PROTECT
#define HEADER_PROTECT

---------- Here is the content of header

#endif

Next, check in your code, are you defining multiple definitions. Or are you re-defining the standard functions again? Can you please post your code to guide you better? Looks like you have re-defined Close_Comm(), can you check it? Error says that the definition is there in main.c also.

接下来,检查您的代码,您是否定义了多个定义。或者您是否再次重新定义标准功能?您能否发布您的代码以更好地指导您?貌似你重新定义了Close_Comm(),可以查一下吗?错误说 main.c 中也有定义。

The following is the general way to compile shared object and link it. To compile shared objects.

下面是编译共享对象并链接它的一般方法。编译共享对象。

-g : for debug information
fPIC: for position independent code
$gcc -fPIC -g myfile

The following will create the shared  object libmyfile.so

$gcc -shared -o libymyfile.so myfile.o

Now,In order to link it with your main.c.
I assume that the libmyfile.so is in your current path, thus -L./

$gcc main.c -o main.out -L./ -lmyfile

Now, you need to export the LD_LIBRARY_PATH on the bash; in order to execute the binary.

$LD_LIBRARAY_PATH=$LD_LIBRARAY_PATH:./
$./main.out

The dlsym is to load the symbol from the shared object at the run-time. If you want to load the shared object at run time, this can be used. The following is one of the example of dlsym Hack the standard function in library and call the native library function afterwards

dlsym 是在运行时从共享对象加载符号。如果要在运行时加载共享对象,可以使用此方法。下面是dlsym hack 库中的标准函数,然后调用原生库函数的例子之一

回答by stdcall

dlsym()is used to find a symbol in an open library file. you first need to use dlopen()in order to open the file, and only then use dlsym()

dlsym()用于在打开的库文件中查找符号。您首先需要使用dlopen()才能打开文件,然后才使用dlsym()