简体   繁体   English

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

[英]How to link and compile with .so file in Linux

I am having .c and .so file. 我有.c和.so文件。 I tried by using the following compilation: gcc main.c -ldl . 我尝试使用以下编译: gcc main.c -ldl In that .c file i linked to .so file through dlsym() . 在那个.c文件中,我通过dlsym()链接到.so文件。 How to compile using .so file with .c. 如何使用.so文件与.c进行编译。

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

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? 看起来您已经重新定义了Close_Comm(),可以检查一下吗? Error says that the definition is there in main.c also. 错误说在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. dlsym将在运行时从共享库中加载符号。 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() is used to find a symbol in an open library file. dlsym()用于在打开的库文件中查找符号。 you first need to use dlopen() in order to open the file, and only then use dlsym() 您首先需要使用dlopen()来打开文件,然后才使用dlsym()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM