31

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

Mohit Deshpande
  • 53,877
  • 76
  • 193
  • 251

2 Answers2

40

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.

aduric
  • 2,812
  • 3
  • 22
  • 16
  • 3
    ... except that you shouldn't be hard-coding the compiler, and you should leverage the predefined build rules... see my tutorial. – Michael Aaron Safyan Apr 09 '10 at 04:26
  • 7
    Well of course you're right. But the OP is relatively new to Makefiles and I just wanted to show the underlying process without any indirection. – aduric Apr 09 '10 at 12:43
  • 3
    "But the OP is relatively new to Makefiles"—which you should start him down the right path rather than putting common errors in his first example. – mk12 Aug 15 '12 at 01:58
  • 7
    Might be crude and hard coded but it helped me a lot to see what I had to do. Walk before you run! – Mike John Sep 22 '13 at 22:59
  • 1
    I thoroughly agree with Mike John _and_ Michael Aaron Safyan. Get the pattern down, but then learn to do it right! – chessofnerd Feb 10 '16 at 18:35
0

GNU make should be what you're looking for.

shinkou
  • 5,138
  • 1
  • 22
  • 32