首先定義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 = 10
hello.h中全局變量g_count初始值改變後,編譯libmyhello.so文件,不編譯main.c文件,直接執行main不會有任何改變,只有重新編譯main.c才能改變g_count輸出值。
動態鏈接庫修改函數中內容後編譯,執行main則會發生改變。