一个用c语言写的程序把他编译成计算机可执行的文件,通常有4个步骤函数
/*================================================================ * Copyright (C) 2018 . All rights reserved. * * 文件名称:helloworld.c * 创 建 者:ghostwu(吴华) * 描 述:gcc编译器用法演示 * ================================================================*/ #include <stdio.h> #define HELLO "hello world!\n" int main(int argc, char *argv[]) { printf( HELLO ); return 0; }
1,预处理:这个步骤,主要是包含头文件,展开宏定义工具
gcc -E helloworld.c -o helloworld.ispa
2,生成汇编代码调试
gcc -S helloworld.i -o helloworld.scode
3,编译汇编blog
gcc -c helloworld.s -o helloworld.o编译器
4,连接io
gcc helloworld.o -o helloworld编译
一般写完程序,咱们用 gcc helloworld.c -o helloworld 直接完成以上四个步骤class
1. -o output_filename
肯定可执行文件的名称为output_filename。若是不给出这个选项,gcc就给出预设的可执行文件名a.out。
2. -c
只编译,不连接成为可执行文件,编译器只是由输入的.c等源文件生成.o为后缀的目标文件。
3. -g
产生调试工具(gdb)所必要的符号信息,要想对编译出的程序进行调试,就必须加入这个选项。
4. -ldirname
将dirname所指出的目录加入到程序头文件目录列表中。
5. -Ldirname
将dirname所指出的目录加入到库文件的目录列表中。
6. -Wall
生成全部警告信息。
helloworld.h
1 ============================================================== 2 * Copyright (C) 2018 . All rights reserved. 3 * 4 * 文件名称:helloworld.h 5 * 创 建 者:ghostwu(吴华) 6 * 描 述: 7 * 8 ================================================================*/ 9 10 #ifndef _HELLO_H_ 11 #define _HELLO_H_ 12 void say_hello( const char* name ); 13 #endif
helloworld.c
/*================================================================ * Copyright (C) 2018 . All rights reserved. * * 文件名称:helloworld.c * 创 建 者:ghostwu(吴华) * ================================================================*/ #include <stdio.h> #include "helloworld.h" void say_hello( const char* name ) { printf( "%s\n", name ); }
main.c
/*================================================================ * Copyright (C) 2018 . All rights reserved. * * 文件名称:main.c * 创 建 者:ghostwu(吴华) * 描 述: * ================================================================*/ #include "helloworld.h" int main(int argc, char *argv[]) { say_hello( "hello ghostwu" ); return 0; }
编译命令:
gcc helloworld.c main.c -o hello
1,首先生成.o文件
gcc -c helloworld.c -o helloworld.o
2,ar rcs libhello.a helloworld.o
r:替换 c:建立 s:保存
把helloworld打包成 libhello.a静态库
3,用静态库编译 生成 可执行文件
gcc -Wall main.c libhello.a -o main
也能够使用l和L 选项
小写的l: 指定库文件名
大写的L: 指定库所在的路径
gcc -Wall main.c -o main2 -lhello( 这种方式会报错,在连接库的时候,没有用L指定路径,默认状况下 不会在当前目录查找静态库 )
gcc -Wall -L. main.c -o main2 -lhello( L后面跟个. 表明当前目录下查找所连接的库(libhello.so) ), -lhello: 省略lib和后缀(.so)
这个时候删除静态库libhello.so,生成的main和main2文件,依然能执行,由于静态库已经被包含在可执行文件中