带有目标文件目录的Makefile

带有目标文件目录的Makefile

本文介绍了带有目标文件目录的Makefile的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对项目具有以下结构,并且我刚刚开始引入Makefile来构建软件:

I have the following structure for a project and I am just starting to introduce a Makefile to build the software:

├── Makefile
├── README.md
├── cg
│   └── cg.c
└── utilities
   ├── utilities.c
   └── utilities.h

我试图将目标文件放在一个名为obj的目录中,但似乎无法正常工作.

I am trying to put object files in a directory called obj yet I can't seem to get it working.

我的makefile看起来像:

My makefile looks like:

CC=mpicc
CFLAGS=-O3 -std=c99
LIBS=
MKDIR_P = mkdir -p

make_build_dir:
    @mkdir -p obj/

utilities.o: utilities/utilities.c
    $(CC) $(CFLAGS) -o ./obj/$@ -c $<

cg.o: cg/cg.c
    $(CC) $(CFLAGS) -o ./obj/$@ -c $<

.PHONY: make_build_dir

cg.exe: make_build_dir utilities.o cg.o
    $(CC) $(CFLAGS) -o $@ $<

clean:
    rm -fr obj
    rm cg.exe

但是这会产生以下错误:

Yet this generates the following error:

a@a:b/b ‹master*›$ make cg.exe
mpicc -O3 -std=c99 -o ./obj/utilities.o -c utilities/utilities.c
mpicc -O3 -std=c99 -o ./obj/cg.o -c cg/cg.c
cg/cg.c:133:3: warning: implicit declaration of function 'decompose' is invalid in C99
      [-Wimplicit-function-declaration]
  decompose(num_chunks, chunks_per_rank,me, &settings);
  ^
1 warning generated.
mpicc -O3 -std=c99 -o cg.exe make_build_dir
clang: error: no such file or directory: 'make_build_dir'
make: *** [cg.exe] Error 1

如何获取它以在obj目录中生成目标文件,然后在顶级目录中生成可执行文件?

How can I get it to generate the object files in the obj directory and then an executable in the top-level directory?

推荐答案

makefile的此链接部分

This linking part of the makefile

cg.exe: make_build_dir utilities.o cg.o
    $(CC) $(CFLAGS) -o $@ $<

有两个问题.首先,$<指目标cg.exe的第一个先决条件,即make_build_dir.在这里将其声明为.PHONY并没有帮助,只是将其传递给$(CC).其次,utilities.o cg.o都不在此位置.您可以将规则更改为

has two issues. First, $< refers to the first prerequesite of the target cg.exe, and that is make_build_dir. Declaring it as .PHONY doesn't help here, it's simply passed to $(CC). Second, utilities.o cg.o both don't exist at this location. You can change the rule to

cg.exe: obj/utilities.o obj/cg.o
    $(CC) $(CFLAGS) -o $@ $^

请注意自动变量$^,它引用了所有先决条件.此外,目标文件目标应为

Note the automatic variable $^ which refers to all prerequisites. Additionally, the object file targets should be

obj/cg.o: cg/cg.c
    $(CC) $(CFLAGS) -o $@ -c $<

(与utilities.o相同).

这篇关于带有目标文件目录的Makefile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 07:27