Makefile-移动目标文件 [英] Makefile - move object files

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

问题描述

经过一番搜索,我设法将以下Makefile放在一起:

After a bit of searching, I've managed to throw together the following Makefile:

CC = gcc
CFLAGS = -c -Wall
LDFLAGS = 
SOURCEFILES = main.c
SOURCES = src/$(SOURCEFILES)
OBJECTS = $(SOURCES:.c=.o)
EXECUTABLE = netsim

all: $(SOURCES) $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS)
    $(CC) $(LDFLAGS) $(OBJECTS) -o $@

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

clean:
    rm -rf netsim $(OBJECTS)

我希望能够将目标文件移动到另一个目录,但是一直在努力使其工作.我想念什么?

I would like to be able to move my object files into another directory, but have been struggling with getting that to work. What am I missing?

推荐答案

诀窍是不要移动对象.
您应该构建在其构建位置使用.

The trick is to not move your objects.
You should build it and use it from where they are built.

例如,您具有以下目录结构:

For example you have the following directory structure:

$ tree .
├── Makefile
├── include
│   └── common_head.h
├── obj
└── src
    ├── foo.c
    └── main.c

手动执行:

$ gcc -o ./obj/foo.o  -c ./src/foo.c  -I ./include  # Build Object #
$ gcc -o ./obj/main.o -c ./src/main.c -I ./include
$ gcc -o exe ./obj/foo.o ./obj/main.o               # Build Executable #


Makefile可以模拟上面的


Makefile to simulate the above

C_FLAGS := -g -Wall -Wextra
CC := gcc
RM := rm
LINKFLAGS := -lanylibrary

.PHONY: $(TARGET)
.PHONY: clean

VPATH:= ./src/ ./obj/ ./include/

# Path for .c , .h and .o Files 
SRC_PATH := ./src/
OBJ_PATH := ./obj/
INC_PATH := -I ./include

# Executable Name 
TARGET := exe

# Files to compile
OBJ1 := foo.o \
        main.o

OBJ := $(patsubst %,$(OBJ_PATH)%,$(OBJ1))

# Build .o first
$(OBJ_PATH)%.o: $(SRC_PATH)%.c
                @echo [CC] $<
                @$(CC) $(C_FLAGS) -o $@ -c $< $(INC_PATH)                  

# Build final Binary
$(TARGET):      $(OBJ)
                @echo [INFO] Creating Binary Executable [$(TARGET)]
                @$(CC) -o $@ $^ $(LINKFLAGS)

# Clean all the object files and the binary
clean:   
                @echo "[Cleaning]"
                @$(RM) -rfv $(OBJ_PATH)*
                @$(RM) -rfv $(TARGET)


所以当你做一个化妆


So when you do a Make

$ make -B
[CC] src/foo.c
[CC] src/main.c
[INFO] Creating Binary Executable [exe]

要进行试运行,请使用make -n

To see a dry-run use make -n

$ make clean ; make -n
g++ -g -Wall -Wextra -o obj/foo.o  -c src/foo.c  -I ./include
g++ -g -Wall -Wextra -o obj/main.o -c src/main.c -I ./include
g++ -o  exe  obj/foo.o obj/main.o -lanylibrary


因此,构建目录结构后,应该如下所示.


So after building your directory structure should look like this.

$ tree .
├── Makefile
├── exe
├── include
│   └── common_head.h
├── obj
│   ├── foo.o
│   └── main.o
└── src
    ├── foo.c
    └── main.c

因此,根据我先前的回答.
您不必使用任何PHONY move,也不必重新创建任何对象.

So from my previous answer.
You don't have to use any PHONY move and also no objects are recreated unnecessarily.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆