Linux C编译器从零开发一

基础程序汇编
test.c
cpp 复制代码
int main() {
  return 42;
}
查看反汇编
bash 复制代码
cc -o test test.c
objdump -d -M intel test
0000000000001129 <main>:
    1129:	f3 0f 1e fa          	endbr64 
    112d:	55                   	push   rbp
    112e:	48 89 e5             	mov    rbp,rsp
    1131:	b8 2a 00 00 00       	mov    eax,0x2a
    1136:	5d                   	pop    rbp
    1137:	c3                   	ret
函数参数汇编
test.c

int plus(int x, int y) {

return x + y;

}

int main() {

return plus(3, 4);

}

.intel_syntax noprefix

.globl plus, main

plus:

add rsi, rdi

mov rax, rsi

ret

main:

mov rdi, 3

mov rsi, 4

call plus

ret

.globl开头表示函数整个程序可见

call原理

  • call将下一条指令(在本例中)ret的地址推入堆栈
  • call跳转到作为参数给出的地址
自定义编译器编译基础程序
test.c
cpp 复制代码
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
  if (argc != 2) {
    fprintf(stderr, "Please input a Number:\n");
    return 1;
  }
  printf(".intel_syntax noprefix\n");
  printf(".globl main\n");
  printf("main:\n");
  printf("  mov rax, %d\n", atoi(argv[1]));
  printf("  ret\n");
  return 0;
}
编译运行
bash 复制代码
cc -o test test.c
./test 42 > test.s
cc -o tmp test.s
./tmp
echo $?
自定义编译器编译加减法程序
test.c
cpp 复制代码
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv) {
  if (argc != 2) {
    fprintf(stderr, "Please input a Number\n");
    return 1;
  }

  char *p = argv[1];

  printf(".intel_syntax noprefix\n");
  printf(".globl main\n");
  printf("main:\n");
  printf("  mov rax, %ld\n", strtol(p, &p, 10));
  // strtol读取数字,读完自动跳到下个符号
  while (*p) {
    if (*p == '+') {
      p++;
      printf("  add rax, %ld\n", strtol(p, &p, 10));
      continue;
    }

    if (*p == '-') {
      p++;
      printf("  sub rax, %ld\n", strtol(p, &p, 10));
      continue;
    }

    fprintf(stderr, "illegal sign '%c'\n", *p);
    return 1;
  }

  printf("  ret\n");
  return 0;
}
编译
bash 复制代码
cc -o test test.c
./test 12+3+4 > tmp.s
cc -o tmp tmp.s
./tmp
echo $?
./test 1*3 > tmp.s //会提示非法符号
测试
test.sh
bash 复制代码
#!/bin/bash
assert() {
  expected="$1"
  input="$2"

  ./chibicc "$input" > tmp.s || exit
  gcc -static -o tmp tmp.s
  ./tmp
  actual="$?"

  if [ "$actual" = "$expected" ]; then
    echo "$input => $actual"
  else
    echo "$input => $expected expected, but got $actual"
    exit 1
  fi
}

assert 0 0
assert 42 42
assert 21 '5+20-4'

echo OK

参考

Compiler Explorer


创作不易,小小的支持一下吧!

相关推荐
qq_25183645727 分钟前
基于java Web 动漫视频网站毕业论文
java·开发语言·前端
野生风长29 分钟前
C++入门基础:从命名空间到引用与指针的全面解析
开发语言·c++
FoldWinCard42 分钟前
D6 Python 基础语法 --- 保留关键字
开发语言·python
风吹心凉2 小时前
python3基础2026.7.22
开发语言·python
qq_452396232 小时前
第五篇:《接口与错误处理:Go 的哲学》
开发语言·后端·golang
Escalating_xu2 小时前
C++可变参数模板与引用折叠精讲
开发语言·c++
wuyk5552 小时前
59.嵌入式C语言高级宏定义实战:多行宏、字符串化与符号拼接
c语言·开发语言·stm32·单片机·嵌入式硬件·物联网·51单片机
云泽8082 小时前
Visual Studio 2026 新手保姆级教程:环境搭建、界面优化与编译器配置详解
开发语言·c++·c·开发工具·visual studio
2zcode3 小时前
基于MATLAB深度学习的乳腺钼靶影像乳腺癌智能诊断系统设计与实现
开发语言·深度学习·matlab·乳腺癌
MoonBit月兔3 小时前
错过大赛报名?MoonBit 开源大赛- 8 月黑客松正式开启
开发语言·ai-native·moonbit