I have written a very simple application in C, for which I would like to have a connection with MySQL database. Here is the code:
我在C中编写了一个非常简单的应用程序,我希望与MySQL数据库建立连接。这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mysql.h>
#include <my_global.h>
void runtime_tile_opt(void);
int main(void) {
runtime_tile_opt();
return 0;
}
void runtime_tile_opt() {
printf("MySQL client version: %s\n", mysql_get_client_info());
}
If i run gcc -o runtime $(mysql_config --cflags) runtime.c $(mysql_config --libs)
, everything works fine, all libraries seemed to be properly linked, and if I run the executable, I get a legitimate-looking output:
如果我运行gcc -o runtime $(mysql_config --cflags)runtime.c $(mysql_config --libs),一切正常,所有库似乎都正确链接,如果我运行可执行文件,我会看到一个合法的输出:
MySQL client version: 5.5.49
However, I would like to make a shared library out of it. So I'm trying to create an object file, with -fPIC
flag:
但是,我想从中创建一个共享库。所以我正在尝试使用-fPIC标志创建一个目标文件:
gcc -c -fPIC runtime.c $(mysql_config --cflags) -o runtime.o $(mysql_config --libs)
The outputs of mysql_config --libs
mysql_config --cflags
are:
mysql_config --libs mysql_config --cflags的输出是:
-L/usr/lib/x86_64-linux-gnu -lmysqlclient -lpthread -lz -lm -ldl
-I/usr/include/mysql -DBIG_JOINS=1 -fno-strict-aliasing -g -DNDEBUG
Finally, I create my .so
:
最后,我创建了我的.so:
gcc runtime.o -shared -o runtime.so
All of the above went with no errors whatsoever. However, some library is not linked apparently, since when I run a file with this plugin loaded, I get:
以上所有都没有任何错误。但是,某些库显然没有链接,因为当我运行加载此插件的文件时,我得到:
/home/michal/thesis/Drafts/runtime/runtime.so: undefined reference to `mysql_get_client_info'
This function is defined in the header files I included. I'm not very experienced with gcc, but I look at it and it looks as though I linked what I had to link. Any ideas where did I fail?
此函数在我包含的头文件中定义。我对gcc不是很有经验,但我看着它,看起来好像我把链接连接起来了。我失败的任何想法?
1 个解决方案
#1
1
You still need to pass the correct -l
flags to the compiler when creating a shared library. They should be the same flags you pass when creating a binary, i.e.
创建共享库时,仍需要将正确的-l标志传递给编译器。它们应该是您在创建二进制文件时传递的相同标志,即
gcc -shared -o runtime.so $(mysql_config --cflags) runtime.o $(mysql_config --libs)
Note that the order of options is important! First pass all options, then all files and lastly libraries (-l...
operands).
请注意,选项的顺序很重要!首先传递所有选项,然后传递所有文件和最后的库(-l ...操作数)。
#1
1
You still need to pass the correct -l
flags to the compiler when creating a shared library. They should be the same flags you pass when creating a binary, i.e.
创建共享库时,仍需要将正确的-l标志传递给编译器。它们应该是您在创建二进制文件时传递的相同标志,即
gcc -shared -o runtime.so $(mysql_config --cflags) runtime.o $(mysql_config --libs)
Note that the order of options is important! First pass all options, then all files and lastly libraries (-l...
operands).
请注意,选项的顺序很重要!首先传递所有选项,然后传递所有文件和最后的库(-l ...操作数)。