Linux环境C编程基础
- /**
- name hellword.c
- @author hg
- */
- int main()
- {
- printf("Hello"n");
- return 0 ;
- }
最简单的编译方法是 gcc hellowrold.c 它会为目标程序生成默认的文件名a.out,直接执行该可执行文件,即可看到输出 。
例如 在shell中输入以下命令:
First : gcc helloworld.c ↙ (即输入回车键) Result :即可生成a.out 可执行文件
Second : ./a.out Result : 执行该文件,即可看到程序输出 。
options为编译选项,GCC总共提供的编译选项超过100个,但只有少数几个会被频繁使用,我们仅对几个常用选项进行介绍。
-o 含义:生成目标文件并且为指定生成的目标文件命名 ,
例如: gcc –o helloworld helloworld.c 那么生成的可执行文件为 hello ,而不是a.out
-c 含义: -c选项告诉GCC仅把源代码编译为目标代码而跳过汇编和连接的步骤,默认生成文件名为 [file_name].o 。
PS: 由于头文件以及引用关系, 我们同样要利用gcc –o 命令为了对相关目标文件进行编译,以便生成一个可执行文件。
假如有三个文件:且相互依赖:
主文件: main.c
- #include <stdio.h>
- #include "first_1.h"
- #include "first_2.h"
- int main()
- {
- printf_str("This is linux c") ;
- print_to_num(10) ;
- return 0 ;
- }
两个头文件
- /*printf_1.h */
- #ifnde _FIRST_H_
- #define _FIRST_H_
- void printf_str(char *str);
- #endif
- /*printf_2.h */
- #ifnde _SECOND_H_
- #define _FIRST_H_
- void print_to_num(int num);
- #endif
真正函数实现的源文件
- /*printf_1.c */
- #include <stdio.h>
- #include "first_1.h"
- void printf_str(char *str)
- {
- printf("%s . I am com" , str);
- }
- /*printf_2.c */
- #include <stdio.h>
- #include "first_2.h"
- void print_to_num(int value)
- {
- int i = 0 ;
- for( ;i < value ;i++)
- printf("cur value is %d ##\n" , i);
- }
1 、 编译:对不同的源文件生成目标文件(xxx.0)
gcc -c main.c ↙ 生成 main.o 目标文件
gcc -c printf_1.c ↙ 生成 printf_1.o 目标文件
gcc -c printf_2.c ↙ 生成 printf_2.o 目标文件
2、 链接:将相关的目标文件链接起来,并形成可执行文件
gcc -c main main.o printf_1.0 printf_2.o ↙ 即可生成可执行文件main
3、 输入 ./main 即可执行该文件并可看到我们程序结果