39
社区成员




一、通过chatgpt学习相关知识
https://chat.openai.com/c/59e97352-da20-4ba0-8ebf-275589ecc453
二、实验楼实验七
1、理解编译链接的过程和 ELF 可执行文件格式
1)首先编写hello.c,并生成编译链接
#include<stdio.h>
int main(){
printf("Hello World!\n");
return 0;
}
编译链接命令
gcc -E hello.c -o hello.i//预处理
gcc -S hello.i -o hello.s//编译
gcc -c hello.s -o hello.o//汇编
gcc hello.o -o hello//链接
“gcc -o hello.static hello.o -static”静态编译出来的hello.static把C库里需要的东西也放到可执行文件里了。使用命令ls –l后,可以看到hello只有8511,hello.static有大概有877147。
编译过程图展示:
int SharedLibApi()
{
printf("This is a shared libary!\n");
return success;
}
3)输入gcc -shared shlibexample.c -o libshlibexample.so -m32”(在64位环境下执行时加上-32)生成.so文件生成文件
#ifdef __cplusplus
extern "C" {
#endif
int DynamicalLoadingLibApi();
#ifndef __cplusplus
}
#endif
#endif /* DL_LIB_EXAMPLE_H */
5)编写dllibexample.c文件
#include<stdio.h>
#include"dllibexample.h"
#define success0
#define failure (-1)
int DynamicalLoadingLibApi()
{
printf("This is a Dynamical Loading libary!\n");
return success;
}
6)使用命令gcc -shared dllibexample.c -o libdllibexample.so生成动态库
7)接着建立动态链接,首先编写主函数test5.c
#include <stdio.h>
#include "shlibexample.h"
#include <dlfcn.h>
int main()
{
printf("This is a Main program!\n");
printf("Calling SharedLibApi() function of libshlibexample.so!\n");
SharedLibApi();
void * handle = dlopen("libdllibexample.so",RTLD_NOW);
if(handle == NULL)
{
printf("Open Lib libdllibexample.so Error:%s\n",dlerror());
return failure;
}
int (*func)(void);
char * error;
func = dlsym(handle,"DynamicalLoadingLibApi");
if((error = dlerror()) != NULL)
{
printf("DynamicalLoadingLibApi not found:%s\n",error);
return failure;
}
printf("Calling DynamicalLoadingLibApi() function of libdllibexample.so!\n");
func();
dlclose(handle);
return success;
}
8)
输入gcc main.c -o main -L/home/shiyanlou -lshlibexample -ldl -m32和export LD_LIBRARY_PATH=$(pwd)以及./test5.c