简体   繁体   English

如何创建Makefile以在C中编译单个任意文件名

[英]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. 我是C编程的新手,我想知道在Makefile中编写什么来编译单个.c文件。

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. 假设我在一个文件夹中有多个.c文件),即sample1.csample2.csample3.c等,我只想编译一个特定的文件名。 I want to only type " make sample2 " which will compile and have an output called sample2 (pretty much the .c name will be maintained). 我想只输入“ make sample2 ”,它将编译并有一个名为sample2的输出(几乎保留.c名称)。

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 . 你不需要makefilemake sample2将编译sample2.c来创建程序sample2

You could use /dev/null as the name of the makefile if you want (or if you need to ignore an existing makefile ): 如果需要,可以使用/dev/null作为makefile的名称(或者如果需要忽略现有的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): 如果你想使用更严格的标志,那么你可以这样做(假设现有的makefile是可消耗的):

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 . 简而言之, make知道如何将单个C文件编译成相应名称的可执行文件(减去.c后缀),而不需要任何显式的makefile You can tweak how it compiles that file if need be. 如果需要,您可以调整它如何编译该文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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