Out of tree builds with makefiles and static pattern rules

那年仲夏 提交于 2019-12-05 02:19:21

Considering/assuming you don't care about portability and are using GNU make, you can use the VPATH feature:

  • Create the directory where you want to do your build.
  • Create a 'Makefile' in that directory with (approximately) the following contents:

    path_to_source = ..
    VPATH = $(path_to_source)
    include $(path_to_source)/Makefile
  • Change the path_to_source variable to point to the root of your source tree.

Additionally you probably need to tweak your original Makefile to make sure that it supports the out of source build. For example, you can't reference to prerequisites from your build rules and instead must use $^ and $<. (See GNU make - Writing Recipes with Directory Search) You might also need to modify the vpath-makefile. For example: adding CFLAGS+=-I$(path_to_source) might be useful.

Also note that if a file is in both your source and build directory, make will use the file in your build directory.

This is a bit old but I was just trying to do the same thing this was the first google hit. I thought it was worth sharing another approach since neither answer is convenient if you're not using autotools and want to be able to build in any directory with a single command and later just blow away that directory.

Here's an example of a Makefile that refers to files relative to the directory containing the Makefile.

MAKEFILE_DIR := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))
MFD := $(MAKEFILE_DIR)

CXX=g++
CXXFLAGS=-std=c++14 -Wall -Wextra -pedantic -c

test: test.o adjacency_pointers_graph.o
    $(CXX) $^ -o $@

%.o: $(MFD)/%.cpp $(MFD)/adjacency_pointers_graph.h
    $(CXX) $(CXXFLAGS) $< -o $@

Then to do an sort of source build:

mkdir build
cd build
make -f ../Makefile
Jack Kelly

On automake

If you use automake, you're pretty much using the entire autotools. automake cannot work without autoconf.

The Makefiles generated by automake support out-of-source builds and cross-compilation, so you should be able to create subdirectories arm/ and thumb/ and run ../configure --host=arm-host-prefix in arm/ and run ../configure --host=thumb-host-prefix in thumb/. (I don't know the actual host tuples that you'd use for each compiler.)

Using GNU make

Since you're using GNUMake, you could do something like this:

ACOBJS := $(addprefix arm/,$(ACSRC:.c=.o))
TCOBJS := $(addprefix thumb/,$(TCSRC:.c=.o))

Use something like this answer to ensure that the arm/ and thumb/ directories (and any subdirectories) exist.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!