Makefile 先編譯出so 後在編譯出執行檔
#include <stdio.h>
int p = 2;
void print()
{
printf("This is the first dll src!\n");
}
#include <dlfcn.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
void* pHandle;
void (*pFunc)();
int* p;
pHandle = dlopen("./dl.so", RTLD_NOW);
if (!pHandle) {
printf("Cann't find dll.so\n");
exit(1);
}
*(void **)(&pFunc) = dlsym(pHandle, "print");
if (pFunc) {
pFunc();
} else {
printf("Cann't find func print\n");
}
p = (int*) dlsym(pHandle, "p");
if (p) {
printf("p=%d\n", *p);
} else {
printf("Cann't find int p\n");
}
dlclose(pHandle);
return 0;
}
gcc -O -fPIC -shared -o dl.so d1.c && gcc -o tds tds.c -ldl
CC = gcc
all: dl.so
$(CC) -o main tds.c -ldl
dl.so:
$(CC) -O -fPIC -shared -o dl.so d1.c
.PHONY: clean
clean:
@rm -rf *.o *.so main