Compile multiple C files with make

混江龙づ霸主 提交于 2019-11-28 16:47:09

问题


(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?


回答1:


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.

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.

It will first look at program and see that to build program, it needs something called main.o and 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).

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

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.




回答2:


GNU make should be what you're looking for.



来源:https://stackoverflow.com/questions/2604398/compile-multiple-c-files-with-make

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!