开发者

Whats the simplest MAKEFILE I could have the works for a single C file?

I have a file called "main.c". Whats the simplest Makefile I can have to compile this file开发者_开发百科 into an executable that I can run like ./blah?


all:
     gcc -o blah main.c

You don't need makefile here, simple shell script is OK.


If you're running GNU Make and if you don't need to link in extra libraries, the simplest makefile is no makefile at all. Try:

make main

If you don't want to have to specify main, then you can use the following one-line Makefile:

all: main

GNU Make has several implicit rules that it uses if you don't define them yourself. The one that makes this work is something like:

%: %.c
        $(CC) $^ -o $@

For more info, see: http://www.gnu.org/software/make/manual/make.html#Using-Implicit


all: blah
blah: main.c
    gcc main.c -o blah


The simplest I would recommend is:

myprog: myprog.o
        $(CC) -o $@ @^

Via implicit rules, this will result in a separate step that compiles myprog.c to myprog.o before linking it. The reason I like this better than the other answer (by Arnaud) is that it scales to more source files without having to enlarge the makefile significantly:

myprog: myprog.o foo.o bar.o helper.o my.o your.o his.o her.o
        $(CC) -o $@ @^


As Jander said, if your source is a single file named blah.c you could use this to output an executable named blah:

all: blah

Or even:

blah:

Everything else is implicit when using GNU make

While this is extremely simple, it does have a few advantages over some of the more complex answers:

  • Compiler is not hardcoded: let your environment choose gcc for you!
  • Your program name is set only once, a good DRY programming practice.
  • Does not create intermediate *.o files which are not needed for this simple project.

That said, I strongly suggest you to improve your Makefile by adding at least clean and all rules and -Wall flags. This can be done with the following Makefile, still keeping all the above advantages:

TARGET=blah
CFLAGS=-Wall

.PHONY: all clean

all: $(TARGET)

$(TARGET):

clean:
    rm -f $(TARGET)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜