如何使用gcc_clang进行C语言的编译_编译的流程是什么?

编译命令

gcc/clang -g -O2 -o -c test test.c -I... -L... -l
-g : 输出文件中的调试信息
-O : 对输出文件做出指令优化,默认是O1, O2优化更多
-c : 可以编译成
-o : 输出文件
-I : 指定头文件
-L : 指定库文件位置
-l : 具体使用哪些库

编译流程

  1. 预编译
  2. 编译
  3. 链接, 动态链接/静态链接

编写文件 add.c

#include <stdio.h>

int add(int a, int b)
{
    return (a+b);
}

clang -g -c add.c // 生成一个指定的add.o的文件

libtool -static -o libmylib.a add.o // 生成一个libmylib.a的文件,必须要lib开头

编写文件 add.h

int add(int a, int b);

编写最终程序

#include <stdio.h>
#include "add.h"

int main(int argc, char *argv[])
{
  int c = add(1, 2);
  printf("c: %d", c)
  return 0;
}

clang -g -o testlib testlib.c -I . -L . -lmylib

最终生成 testlib 的文件, libmylib.a 的库必须要去掉 lib开头和结尾的.a


clang -g -o testlib testlib.c -I . -L . -lmylib // -I . 头文件在当前目录的意思, -L . -lmylib是指定文件的意思