为了方便查找,转载了一个博主的文章。
文件:
库 hello.cpp hello.h
测试 main.cpp
编译 Makefile
hello.h
#include
class test{
private:
int m_num;
public:
test(int num);
~test();
int get_num();
void set_num(int num);
};
hello.cpp
#include “hello.h”
test::test(int num)
: m_num (num){
}
test::~test(){}
int test::get_num()
{
return m_num;
}
void test::set_num(int num)
{
m_num = num;
}
main.cpp
#include “hello.h”
using namespace std;
int main(int argc, char **argv)
{
test *t = new test(5);
cout << t->get_num();
}
Makefile
all:libtest.so test
libtest.so:hello.h hello.cpp
g++ -fPIC -shared -o libtest.so hello.cpp
test:main.cpp libtest.so
g++ -o test main.cpp -ltest -L./
install:
cp libtest.so /usr/lib
clean:
sudo rm -rf /usr/lib/libtest.so
rm -rf libtest.so test
运行结果
$ ./test
5
选项参数
gcc -I :指定头文件的搜索路径
gcc -L :指定库链接的搜索路径
注:若想要使用第三方静态库,不能使用gcc的-static选项,因为-static时生成静态链接可执行程序,所有的库都使用静态库(但我们只想这个第三方库使用静态库,而不是所有),因此我们是将第三方库拷贝到指定的路径下,使用-L选项指定库的链接搜索路径,那么这时候链接的就是静态库。
原文链接:https://blog.csdn.net/tornadory/article/details/5808614