3

Let's say I have a project where I've already run CMake in .build directory:

project/
    .build/
    .src

Presently I must do this to run the build:

cd .build
make

I'd like to be able to run make from the root of my project, perhaps with

make -f ./build/Makefile

but it doesn't work. I get errors like this

make[1]: CMakeFiles/Makefile2: No such file or directory
make[1]: *** No rule to make target `CMakeFiles/Makefile2'.  Stop.
make: *** [all] Error 2

This is because the CMake-generated Makefile assumes its working directory is the same as where it resides (.build).

Is it possible to have CMake generate a makefile such that the makefile changes the working directory to where it resides?

2 Answers 2

7

You just need to tell make where is your base directory, no need to change cmake.

make -C your_build_directory
1
  • This method is helpful because it allows make from any directory and has normal access to all the targets - including for tab completion. Feb 11, 2014 at 23:08
0

Another approach would be to create another Makefile in the directory you want to run make from, with contents something like:

all:
       cd ./build;  make $(MFLAGS)

Then you could just type "make" from the top level directory.

I don't think there is a way to get cmake to generate a Makefile that can be run from any location. That's just not how make is ordinarily used.

But you might be able to coax cmake into creating an additional helper makefile in your project root directory, with some cmake like the following in CMakeLists.txt:

configure_file(ProjectRootMakefile.in ${CMAKE_SOURCE_DIR}/Makefile @ONLY)

(If needed, replace that "${CMAKE_SOURCE_DIR}" with an expression that resolves to your project root directory)

And you need to create the file ProjectRootMakefile.in in your source tree, with contents like:

all:
       cd @CMAKE_BINARY_DIR@; make $(MFLAGS)

which will be used as the template for your project root Makefile. (Ensure that you use a tab character, not spaces, before the "cd")

I haven't tested these suggestions, but there should be enough here to give you the general idea.

2
  • This is an interesting idea... Any thoughts on how to get CMake to put all the targets into the top-level makefile?
    – paleozogt
    Jan 19, 2010 at 20:54
  • You might consider using an old-school in-source build process. It's deprecated these days, but used to be the norm. Put the CMakeLists.txt file in the project root directory. "ccmake -i .", "make", "make whatever", and "make install" right there. Your sources will be mixed with your binaries, and purist will poohpooh, but it might satisfy your needs. Jan 19, 2010 at 23:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.