简体   繁体   中英

How to create Makefile to compile a single arbitrary filename in C

I'm very new to C programming and I want to know what to write in a Makefile to compile a single .c file.

Say I have a multiple .c files in one folder )namely sample1.c , sample2.c , sample3.c , etc) and I only want to compile a specific filename. I want to only type " make sample2 " which will compile and have an output called sample2 (pretty much the .c name will be maintained).

I've read several solutions and someone might have suggested this but didn't work.

SRC =  $(shell find . -type f -name \*.c)

executable: $(SRC:.c=.o)
    gcc -std=gnu99  $@ $^ 

What do I need to do to make it work?

Converting a comment into an answer.

You don't need a makefile for that: make sample2 will compile sample2.c to create the program sample2 .

You could use /dev/null as the name of the makefile if you want (or if you need to ignore an existing makefile ):

make -f /dev/null sample2

That compiles with the default options, of course. If you want to use more stringent flags, then you might do this (assuming that the existing makefile is expendable):

echo 'CFLAGS = -Wall -Wextra -Werror -std=c11 -O3 -g' > makefile
make sample2

or some variant on that theme, such as:

make -f /dev/null CFLAGS="-Wall -Wextra -Werror -std=c11 -O3 -g" sample2

In short, make knows how to compile single C files into the executable of the corresponding name (minus the .c suffix) without needing any explicit makefile . You can tweak how it compiles that file if need be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM