首先定义hello.c文件
#include <stdio.h>
void hello(const char * name)
{
printf("Hello , %s!\n", name);
}
定义hello.h头文件
#ifndef HELLO_H
#define HELLO_H
int g_count = 100;
void hello(const char* name);
#endif //HELLO_H
编译:
gcc -fPIC -c hello.c
gcc -shared -o libmyhello.so hello.o
或者:gcc -fPIC -shared -o libmyhello.so hello.c
拷贝libmyhello.so到/usr/lib/下或者使用 LD_LIBRARY_PATH=. ./XXX 指定链接位置。
定义test.c文件
#include "hello.h"
void Test(const char * name)
{
hello(name);
}
定义test.h头文件
void Test(const char* name);
编译:
gcc -fPIC -c test.c
gcc -shared -o libtest.so test.o -L. -lmyhello
或者:gcc -fPIC -shared -o libmyhello.so test.c -L. -lmyhello
定义main.c文件
#include "test.h"
#include "hello.h"
#include <stdio.h>
extern int g_count;
int main()
{
Test("everyone");
printf("count = %d\n", g_count);
return 0;
}
编译:gcc -o main main.c -L. -lmyhello -ltest
执行main可执行程序,输出如下:
Hello , everyone!
count = 100
hello.h中全局变量g_count初始值改变后,编译libmyhello.so文件,不编译main.c文件,直接执行main不会有任何改变,只有重新编译main.c才能改变g_count输出值。
动态链接库修改函数中内容后编译,执行main则会发生改变。