C语言 用make编译多个C文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2604398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:07:22  来源:igfitidea点击:

Compile multiple C files with make

cmakefilecompilationmodular

提问by Mohit Deshpande

(I am running Linux Ubuntu 9.10, so the extension for an executable is executablefile.out) I am just getting into modular programming (programming with multiple files) in C and I want to know how to compile multiple files in a single makefile. For example, what would be the makefile to compile these files: main.c, dbAdapter.c, dbAdapter.h? (By the way, If you haven't figured it out yet, the main function is in main.c) Also could someone post a link to the documentation of a makefile?

(我正在运行 Linux Ubuntu 9.10,因此可执行文件的扩展名是 executablefile.out)我刚刚进入 C 中的模块化编程(使用多个文件编程),我想知道如何在单个 makefile 中编译多个文件。例如,编译这些文件的 makefile 是什么:main.c、dbAdapter.c、dbAdapter.h?(顺便说一句,如果您还没有弄清楚,主要功能在 main.c 中)还有人可以发布一个指向 makefile 文档的链接吗?

回答by aduric

The links posted are all good. For you particular case you can try this. Essentially all Makefiles follow this pattern. Everything else is shortcuts and macros.

发布的链接都很好。对于你的特殊情况,你可以试试这个。基本上所有的 Makefile 都遵循这个模式。其他一切都是快捷方式和宏。

program: main.o dbAdapter.o
   gcc -o program main.o dbAdapter.o

main.o: main.c dbAdapter.h
   gcc -c main.c

dbAdapter.o dbAdapter.c dbAdapter.h
   gcc -c dbAdapter.c

The key thing here is that the Makefile looks at rules sequentially and builds as certain items are needed.

这里的关键是 Makefile 按顺序查看规则并在需要某些项目时进行构建。

It will first look at program and see that to build program, it needs something called main.o and dbAdapter.o.

它将首先查看程序并看到要构建程序,它需要名为 main.o 和 dbAdapter.o 的东西。

It will then find main.o. However, to build main.o, it will need main.c and dbAdapter.h (I assume dbAdapter.h is included in main.c).

然后它会找到 main.o。但是,要构建 main.o,它需要 main.c 和 dbAdapter.h(我假设 dbAdapter.h 包含在 main.c 中)。

It will use those sources to build main.o by compiling it using gcc. The -c indicates the we only want to compile.

它将使用这些源代码通过 gcc 编译来构建 main.o。-c 表示我们只想编译。

It does the same thing with dbAdapter.o. When it has those two object files, it is ready to link them. It uses the gcc compiler for this step as well. The -o indicates that we are creating a file called program.

它对 dbAdapter.o 做同样的事情。当它拥有这两个目标文件时,就可以链接它们了。这一步也使用 gcc 编译器。-o 表示我们正在创建一个名为 program.c 的文件。

回答by shinkou

GNU makeshould be what you're looking for.

GNU make应该是你要找的。