20231321王曦轶课上测试
完成下面任务(29 分)
首先,我推荐你在 openEuler 系统中完成这些任务,这对你未来就业很有帮助。让我们开始吧:
1. 编写 hello.c 并记录 git 过程
hello.c
include <stdio.h>
int main() {
printf("hello 20231321 王曦轶\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
运行结果:
./hello 会输出 "hello 20231321 王曦轶"
git记录
git init
git add .
git commit -m "添加hello.c和编译过程"
2. 判断大小端的模块
创建 endian.h:
c
复制
ifndef ENDIAN_H
define ENDIAN_H
int is_little_endian();
int is_big_endian();
endif
创建 endian.c:
c
include "endian.h"
int is_little_endian() {
int num = 1;
return *(char *)&num == 1;
}
int is_big_endian() {
return !is_little_endian();
}
创建 main.c:
c
include <stdio.h>
include "endian.h"
int main() {
if (is_little_endian()) {
printf("小端模式\n");
} else {
printf("大端模式\n");
}
return 0;
}
编译运行:
gcc -c endian.c -o endian.o
gcc main.c endian.o -o main
./main
- 制作和使用库
静态库:
ar rcs libendian.a endian.o
gcc main.c -L. -lendian -o main_static
共享库:
gcc -shared -fPIC endian.c -o libendian.so
export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
gcc main.c -L. -lendian -o main_shared
- 按指定结构组织代码
创建目录结构:
复制
project/
├── bin/
├── include/endian.h
├── lib/
└── src/
├── endian.c
└── main.c
编译过程:
bash
复制
编译源文件
gcc -c src/endian.c -I include -o endian.o
gcc -c src/main.c -I include -o main.o
制作静态库
ar rcs lib/libendian.a endian.o
制作动态库
gcc -shared -fPIC src/endian.c -I include -o lib/libendian.so
编译使用库
gcc src/main.c -I include -L lib -lendian -o bin/main
- 补充 Makefile
在项目根目录创建 Makefile:
makefile
复制
all: bin/main
bin/main: src/main.c lib/libendian.a
gcc src/main.c -I include -L lib -lendian -o bin/main
lib/libendian.a: src/endian.c include/endian.h
gcc -c src/endian.c -I include -o endian.o
ar rcs lib/libendian.a endian.o
rm endian.o
clean:
rm -f bin/* lib/.a lib/.so