加入收藏 | 设为首页 | 会员中心 | 我要投稿 汽车网 (https://www.0577qiche.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 编程要点 > 语言 > 正文

GCC编译多文件项目

发布时间:2023-05-26 14:06:46 所属栏目:语言 来源:
导读:在一个 C(或者 C++)项目中,往往在存储多个源文件,如果仍按照之前“先单独编译各个源文件,再将它们链接起来”的方法编译该项目,需要编写大量的编译指令,事倍功半。事实上,利用 gcc 指令可以同时处理
在一个 C(或者 C++)项目中,往往在存储多个源文件,如果仍按照之前“先单独编译各个源文件,再将它们链接起来”的方法编译该项目,需要编写大量的编译指令,事倍功半。事实上,利用 gcc 指令可以同时处理多个文件的特性,可以大大提高我们的工作效率。

举个例子,如下是一个拥有 2 个源文件的 C 语言项目:
[root@bogon demo]# ls
main.c  myfun.c
[root@bogon demo]# cat main.c
#include <stdio.h>
int main(){
    display();
    return 0;
}
[root@bogon demo]# cat myfun.c
#include <stdio.h>
void display(){
    printf("GCC:http://c.biancheng.net/gcc/");
}
[root@bogon demo]#

可以看到,该项目中仅包含 2 个源文件,其中 myfun.c 文件用于存储一些功能函数,以方便直接在 main.c 文件中调用。

对于此项目,我们可以这样编译:
[root@bogon demo]# ls
main.c  myfun.c
[root@bogon demo]# gcc -c myfun.c main.c
[root@bogon demo]# ls
main.c  main.o  myfun.c  myfun.o
[root@bogon demo]# gcc myfun.o main.o -o main.exe
[root@bogon demo]# ls
main.c  main.exe  main.o  myfun.c  myfun.o
[root@bogon demo]# ./main.exe
GCC:http://c.biancheng.net/gcc/

甚至于,gcc 指令还可以直接编译并链接它们:
[root@bogon demo]# gcc myfun.c main.c -o main.exe
[root@bogon demo]# ls
main.c  main.exe  myfun.c
[root@bogon demo]# ./main.exe
GCC:http://c.biancheng.net/gcc/

以上 2 种方式已然可以满足大部分场景的需要。但值得一提的是,如果一个项目中有十几个甚至几十个源文件,即便共用一条 gcc 指令编译(并链接),编写各个文件的名称也是一件麻烦事。

为了解决这个问题,我们可以进入该项目目录,用 *.c 表示所有的源文件,即执行如下指令:
[root@bogon demo]# ls
main.c  myfun.c
[root@bogon demo]# gcc *.c -o main.exe
[root@bogon demo]# ls
main.c  main.exe  myfun.c
[root@bogon demo]# ./main.exe
GCC:http://c.biancheng.net/gcc/

由此,大大节省了手动输入各源文件名称的时间。

(编辑:汽车网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章