静态库
在系统提示符下键入以下命令得到hello.o文件
gcc -c hello.cpp
在系统提示符下键入以下命令将创建静态库文件libmyhello.a
ar crv libmyhello.a hello.o
在程序中使用静态库
gcc -o hello2 m.cpp -L. -lmyhello
动态库生成具有-shared -fPIC的hello.ogcc -shared -fPIC -c hello.cpp生成动态库libmyhello2.sogcc -shared -fPIC -o libmyhello2.so hello.o编译(-Wl,--rpath=.要与-L配合)gcc -o hello m.cpp -L. -lmyhello2 -Wl,--rpath=.gcc -o hello2 m.cpp -L ./1 -lmyhello -Wl,--rpath=./1
附录:
在linux下,默认只到/lib、/usr/lib和/usr/local/lib查找,找不到程序将无法启动。gcc编译链接动态库时,很有可能编译通过,但是执行时,找不到动态链接库,那是
因为-L选项指定的路径只在编译时有效,编译出来的可执行文件不知道-L选项后面的值,当然找不到。
解决方法是通过-Wl,--rpath=<your_lib_dir>,使得可执行文件记住链接库的位置.
ldd
显示程序依赖的动态共享库,
以及库文件能否被找到
例子:ldd hello
#include <stdio.h>
void hello(const char *name)
{
printf("%s!\n", name);
}
#ifndef HELLO_H
#define HELLO_H
void hello(const char *name);
#endif
#include "hello.h"
int main()
{
hello("hello world");
return 0;
}