dlopen在 mysql_init 段错误

czg2013czg 2013-01-23 03:10:11
我用动态链接库和mysql链接
main.cpp是这样的
#include <iostream>
#include <dlfcn.h>
#include<stdio.h>
#include<mysql/mysql.h>
int main(int argc,char ** argv) {
using std::cout;
using std::cerr;
char * word = argv[1];
cout << "C++ dlopen demo\n\n";

// open the library
cout << "Opening hello.so...\n";
dlopen("/usr/lib/mysql/libmysqlclient.so",RTLD_LAZY);
void* handle = dlopen("./hello.so", RTLD_LAZY);
int (*hello)(char *str);
if (!handle) {
cerr << "Cannot open library: " << dlerror() << '\n';
return 1;
}

// load the symbol
cout << "Loading symbol hello...\n";
// typedef void (*hello_t)();

// reset errors
dlerror();
hello = (int (*)(char *)) dlsym(handle, "test");
const char *dlsym_error = dlerror();
if (dlsym_error) {
cerr << "Cannot load symbol 'hello': " << dlsym_error <<
'\n';
dlclose(handle);
return 1;
}

// use it to do the calculation
cout << "Calling hello...\n";
(*hello)(word);
// printf("%s\n",(*hello("ffff")));
// close the library
cout << "Closing library...\n";
dlclose(handle);
}


hello.cpp是这样的
#include <iostream>
#include <stdio.h>
#include <time.h>
#include <mysql/mysql.h>
#include <cstdlib>
extern "C" void hello() {
std::cout << "helo" << '\n';
}
extern "C" void test(char *str){
std::cout<<"test1"<<'\n';
MYSQL conn_ptr;
std::cout<<"test3"<<'\n';
mysql_init(&conn_ptr);
std::cout<<"test2"<<'\n';
if(mysql_real_connect(&conn_ptr,"127.0.0.1","root","","test",0,NULL,0)){
printf("success\n");
mysql_close(&conn_ptr);
}
else {
fprintf(stderr,"error");
if(mysql_errno(&conn_ptr)){
fprintf(stderr,"%d : %s",mysql_errno(&conn_ptr),mysql_error(&conn_ptr));
}
printf("connection failed\n");
}
mysql_close(&conn_ptr);
//return EXIT_SUCCESS;
}

在编译hello.cpp成.so文件时候报错
root@ubuntu:/srv/text/dlopen# g++ -shared -fPIC -L /usr/lib/mysql -lmysqlclient -o hello.so hello.cpp
hello.cpp: In function 'void test(char*)':
hello.cpp:27:9: error: return-statement with a value, in function returning 'void' [-fpermissive]
去掉最后一行之后编译没有问题

但是在运行./main的时候,只有输出了test1和test3,之后就是段错误
在mysql_init的时候
不知道是什么原因
...全文
144 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
mymtom 2013-01-23
  • 打赏
  • 举报
回复
只有一处可疑 test的返回类型是void. 在main.cpp里却用的是int型 不知道这个有没有关系。
lee_鹿游原 2013-01-23
  • 打赏
  • 举报
回复
引用 3 楼 czg2013czg 的回复:
把这里的代码copy回去,段错误没了 不知道怎么回事 弄了一下午 段错误自己会解决的吗
语法上没看出问题,可能和环境有关,楼主能调试看相关值,以及错误记录,翻阅相关资料,对照。
czg2013czg 2013-01-23
  • 打赏
  • 举报
回复
把这里的代码copy回去,段错误没了 不知道怎么回事 弄了一下午 段错误自己会解决的吗
lee_鹿游原 2013-01-23
  • 打赏
  • 举报
回复
去掉最后一行之后编译没有问题,那是因为 你的函数返回类型是void,只能return;
赵4老师 2013-01-23
  • 打赏
  • 举报
回复
进程意外退出会在当前目录下产生形如‘core.数字’的文件比如‘core.1234’ 使用命令 gdb 运行程序名 core.数字 进入gdb然后使用bt命令 可以查看进程意外退出前函数调用的堆栈,内容为从上到下列出对应从里层到外层的函数调用历史。 如果进程意外退出不产生core文件,参考“ulimit -c core文件最大块大小”命令

64,281

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧