简体   繁体   English

将 makefile 与多个 C 程序一起使用

[英]Using makefile with multiple C programs

I've written multiple C programs in different files and I want to run all three of them in the same time, on the same argv:我在不同的文件中编写了多个 C 程序,我想在同一个 argv 上同时运行所有三个程序:

That's what I tried so far but its only running the last program digcmp.c:这就是我到目前为止所尝试的,但它只运行最后一个程序 digcmp.c:

CC=gcc
a_OBJS=lexcmp.o
b_OBJS=lencmp.o
c_OBJS=digcmp.o
EXEC=lex len dig
DEBUG = -g
CFLAGS = -std=c99  -Wall -Werror $(DEBUG)  #if you have CFLAGS you do not have to write for each file $(CC) -c $*.c!!!

lex: $(b_OBJS)
    $(CC) $(a_OBJS) -o $@


len: $(b_OBJS)
    $(CC) $(b_OBJS) -o $@


dig: $(c_OBJS)
    $(CC) $(c_OBJS) -o $@


lexcmp.o: lexcmp.c
lencmp.o: lencmp.c
digcmp.o: digcmp.c


clean: 
    rm -f lex $(a_OBJS)
    rm -f len $(b_OBJS)
    rm -f dig $(c_OBJS)

The make program have many implicit rules . make程序有很多隐含的规则 In fact they are what makes your lexcmp.o: lexcmp.c (etc.) rules work.事实上,正是它们使您的lexcmp.o: lexcmp.c (等)规则起作用。

All you need is to list the rules to make the executable programs themselves:您所需要的只是列出制作可执行程序本身的规则:

lexcmp: lexcmp.o
lencmp: lencmp.o
digcmp: digcmp.o

The above is a perfectly fine Makefile on its own, and if you run eg以上是一个非常好的Makefile本身,如果你运行例如

$ make lencmp

then the lencmp.c source file will be built into the object file lencmp.o which will then be linked into the executable lencmp program.然后lencmp.c源文件将被构建到 object 文件lencmp.o中,然后链接到可执行的lencmp程序中。

If you want specific compilation flags when building just set the CFLAGS variable and it will be used automatically.如果您在构建时需要特定的编译标志,只需设置CFLAGS变量,它将自动使用。 I also recommend a default target which might list all executable targets as dependencies to build all of them:我还推荐一个默认目标,它可能将所有可执行目标列为依赖项以构建所有这些目标:

CFLAGS = -Wall -Wextra

.PHONY: all
all: lexcmp lencmp digcmp

This should really be enough to build all your executable files (skipping the object-file intermediate stage) with the flags you want.这真的应该足以用你想要的标志构建你所有的可执行文件(跳过目标文件中间阶段)。

The .PHONY target tells make that it's not supposed to generate a file with the name all . .PHONY目标告诉make它不应该生成名称为all的文件。

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

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