how to compile these code(simple share library)

h3w4 2007-01-12 02:23:19
/////////////sharelib.h
#ifndef _SHARE_LIB_
#define _SHARE_LIB_
void fun();
#endif

/////////////sharelib.cpp
#include "sharelib.h"
#include <iostream>

void fun()
{
std::cout << "int fun" << std::endl;
}

//////////////////////////////
/////////////////main.cpp
extern void (*fun)();
int main()
{
fun();
return 0;
}

//////////////////////////compile code
#g++ -c -fPIC sharelib.cpp -o libshare.0 // pass

#ld -shared -soname sharelib.1 libshare.0 -o libshare.so // pass

#ls -l
-rw-r--r-- 1 root root 2584 Jan 12 14:24 libshare.0
-rwxr-xr-x 1 root root 3794 Jan 12 14:24 libshare.so
-rw-r--r-- 1 hh users 63 Jan 12 13:55 main.cpp
-rw-r--r-- 1 root root 213 Jan 12 14:01 makefile
-rw-r--r-- 1 root root 121 Jan 12 14:05 sharelib.cpp
-rw-r--r-- 1 root root 63 Jan 12 14:05 sharelib.h

#g++ -o sharetest main.cpp -L./ -lshare // error

//////////////////////////error message:
/tmp/ccy9frxb.o: In function `main':
main.cpp:(.text+0x12): undefined reference to `fun'
/usr/lib/gcc/i586-suse-linux/4.1.0/../../../../i586-suse-linux/bin/ld: sharetest: hidden symbol `__dso_handle' in /usr/lib/gcc/i586-suse-linux/4.1.0/crtbegin.o is referenced by DSO
/usr/lib/gcc/i586-suse-linux/4.1.0/../../../../i586-suse-linux/bin/ld: final link failed: Nonrepresentable section on output
collect2: ld returned 1 exit status











...全文
360 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhousqy 2007-01-12
  • 打赏
  • 举报
回复
debian:~/learn# export LD_LIBRARY_PATH=.
debian:~/learn# ./a.out
int fun
debian:~/learn#
h3w4 2007-01-12
  • 打赏
  • 举报
回复
to zhousqy(标准C匪徒)(甩拉,甩拉)

i do so
#g++ -fPIC -shared -o libshare.so sharelib.cpp
#g++ main.cpp -L. -lshare -o tst

but when i run it, it occurs again

tst: error while loading shared libraries: libshare.so: cannot open shared object file: No such file or directory
zhousqy 2007-01-12
  • 打赏
  • 举报
回复
$g++ -fPIC -shared -o libshare.so sharelib.cpp
$g++ main.cpp -L. -lshare
h3w4 2007-01-12
  • 打赏
  • 举报
回复
thanks first
i modify the main.cpp

#include "sharelib.h"
int main()
{
fun();
return 0;
}

and compile
#g++ -o sharetest main.cpp -L./ -lshare

////////////////////////////////////error message
/usr/lib/gcc/i586-suse-linux/4.1.0/../../../../i586-suse-linux/bin/ld: sharetest: hidden symbol `__dso_handle' in /usr/lib/gcc/i586-suse-linux/4.1.0/crtbegin.o is referenced by DSO
/usr/lib/gcc/i586-suse-linux/4.1.0/../../../../i586-suse-linux/bin/ld: final link failed: Nonrepresentable section on output
collect2: ld returned 1 exit status

there still have promble, where i did wrong???
a_b_c_abc6 2007-01-12
  • 打赏
  • 举报
回复
//extern void (*fun)();这是声明一个函数指针
extern void fun();//修改为这样
int main()
{
fun();
return 0;
}

64,648

社区成员

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

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