一、学习并掌握可执行程序的编译、组装过程
A. 在Linux系统(Ubuntu)下仿做一遍
-
准备过程
-
创建文件:
hello.c
,hello.h
,main.c
-
编辑代码并生成
hello.o
文件, check withls
-
-
由.o 文件创建静态库
- Naming convention:
libmyhello.a
- Command:
ar -crv libmyhello.a hello.o
- Check with
ls
- Naming convention:
-
在程序中使用静态库
- Generate
main.o
withgcc -c main.c
- Command:
gcc -o hello main.c libmyhello.a
- Generate executable:
./hello
- Generate
-
由.o 文件创建动态库文件
-
(1) Create shared library:
libmyhello.so
-
(2) Execute with dynamic library:
gcc -o hello main.c -L.
-
B. 第一次作业的程序代码改编
-
准备过程
- 创建文件:
sub1.c
,sub2.c
,main1.c
- Edit code
- 创建文件:
-
生成.o文件并查看
- Command:
gcc -c sub1.c sub2.c
- Command:
-
静态库
- Command:
ar crv libsub.a sub1.o sub2.o
- Linking:
gcc -o main main.c libsub.a
- Command:
-
动态库
- Command:
gcc -shared -fPIC -o libsub.so sub1.o sub2.o
- Linking:
gcc -o main main.c libsub.so
- Check with
ls
- Command:
-
动态静态库对比
二、Gcc不是一个人在战斗
解读GCC编译工具集和EFF文件格式
- 学习任务:仿做材料“Linux GCC常用命令.pdf”和“GCC编译器背后的故事.pdf”
代码处理过程
-
生成
.i
文件并查看:gcc -E hello.c -o hello.i
-
预处理:删除宏定义、处理条件预编译指令、插入被包含文件、删除注释、添加行号和文件标识
-
编译:
gcc -S hello.i -o hello.s
三、全局常量、全局变量、局部变量、静态变量、堆、栈等概念
A. 在Ubuntu上进行验证
-
编辑
main.c
文件及代码
-
执行
./main
B. STM32中代码演示
#include “stm32f10x.h”
#include “stdio.h”
void func() {
int local_var = 300; // 局部变量
USART_InitTypeDef USART_InitStructure;
// 初始化串口
// ...
while (1) {
char buffer[64];
sprintf(buffer, "Local var address in STM32: %p\n", &local_var);
for (int i = 0; buffer[i] != '\0'; i++) {
USART_SendData(USART2, buffer[i]);
while (USART_GetFlagStatus(USART2, USART_FLAG_TXE) == RESET);
}
}
}
int main() {
int global_var = 200; // 全局变量
USART_InitTypeDef USART_InitStructure;
// 初始化串口
// ...
while (1) {
char buffer[64];
sprintf(buffer, "Global var address in STM32: %p\n", &global_var);
for (int i = 0; buffer[i] != '\0'; i++) {
USART_SendData(USART2, buffer[i]);
while (USART_GetFlagStatus(USART2, USART_FLAG_TXE) == RESET);
}
func();
}
}
- 编译成功,将代码烧录进入芯片,按下reset键,单片机发送数据,串口调试助手结果。