简体   繁体   English

在C中与多个文件一起使用Makefile

[英]Using Makefile in C with more than one file

I have 6 files: 我有6个文件:

guiGame.c, which include guiGame.h
guiGame.h, include minimax.h,listutils.h
minimax.c, include minimax.h
minimax.h, include listutils.h 
listutils.c, include listutils.h

I built it in Visual Studio and I need to run it on Linux. 我是在Visual Studio中构建的,需要在Linux上运行。 I tried to search how to build makefile for them but I didn't succeed to build something that works; 我试图搜索如何为他们构建makefile,但是我没有成功构建能够运行的文件。 there's something with the including that never works for me. 其中包含的某些内容对我不起作用。

Can someone tell me what I need to write in every X:<files> line? 有人可以告诉我我需要在每X:<files>行中写什么吗?

Thanks. 谢谢。

The basics: 基础:

SRCS = guiGame.c minimax.c listutils.c
HDRS = guiGame.h minimax.h listutils.h

PROG = guiGame
OBJS = ${SRCS:.c=.o}

DEBRIS = a.out core *~
RM_F   = rm -f

all: ${PROG}

${PROG}: ${OBJS}
    ${CC} -o $@ ${CFLAGS} ${OBJS} ${LDFLAGS} ${LDLIBS}

clean:
    ${RM_F} ${OBJS} ${PROG} ${DEBRIS}

The residual issue is getting the dependencies correct. 剩余的问题是使依赖关系正确。 The object files depend on the headers they include. 目标文件取决于它们包含的标题。 The pessimistic but simple version is: 悲观但简单的版本是:

${OBJS}: ${HDRS}

It works, but it means that if you change guiGame.h , listutils.o will be recompiled when it otherwise need not be. 它可以工作,但是这意味着如果您更改guiGame.h ,则在不需要时会重新编译listutils.o

There are various tools that automate the handling of dependencies. 有多种工具可以自动处理依赖关系。 mkdep and mkdepend are two; mkdepmkdepend是两个; you can also investigate the options to gcc . 您还可以研究gcc的选项。

Note that the command lines (starting ${CC} and ${RM_F} ) are indented by tabs, not spaces. 请注意,命令行(以${CC}${RM_F} )由制表符(而不是空格)缩进。 This is crucial. 这很关键。

The variable LDFLAGS is for specifying library locations (primarily). 变量LDFLAGS用于(主要)指定库位置。 The variable LDLIBS allows you to specify the libraries. 变量LDLIBS允许您指定库。 Object files go before libraries on the command line; 在命令行上,目标文件位于库之前。 the library flags can be placed anywhere. 库标志可以放置在任何地方。

I normally build CFLAGS from various parts: 我通常从各个部分构建CFLAGS

WFLAG1 = -Wall
WFLAG2 = -Wextra
WFLAG3 = -Wmissing-prototypes
WFLAG4 = -Wstrict-prototypes
WFLAG5 = -Wold-style-definition
WFLAG6 = -Werror
WFLAGS = ${WFLAG1} ${WFLAG2} ${WFLAG3} ${WFLAG4} ${WFLAG5} ${WFLAG6}
SFLAGS = -std=c11
GFLAGS = -g
OFLAGS = -O3
UFLAGS = # Set on command line
IFLAG1 = -I${HOME}/inc
IFLAGS = ${IFLAG1}

CFLAGS  = ${OFLAGS} ${GFLAGS} ${IFLAGS} ${SFLAGS} ${WFLAGS} ${UFLAGS}

This allows me to adjust any option on the make command line. 这使我可以在make命令行上调整任何选项。 Most people aren't so fussy (careful?). 大多数人不是那么挑剔(小心吗?)。 Note that GFLAGS is historically used for flags to the SCCS get command — you might screw something up by recycling it, but you probably won't. 请注意, GFLAGS过去用于SCCS get命令的标志-您可以通过回收它来GFLAGS某些东西,但可能不会。

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

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