4

I have a project with existing makefile based build system, where I want to add existing cmake based component.

What is best way to integrated cmake configure step? As a $(shell ) call evaluating some variable? That runs configure on each invocation...

How to integrate building itself? Just (MAKE) -C cmake-build-dir [targets]?

kwesolowski
  • 695
  • 8
  • 18

2 Answers2

4

The goal of CMake is to generate a Makefile, so I would go with something like this:

CMAKE_BUILD_DIR := some_dir
CMAKE_SOURCE_DIR := some_src_dir

$(CMAKE_BUILD_DIR)/Makefile: $(CMAKE_SOURCE_DIR)/CMakeLists.txt
    cmake -S $(<D) -B $(@D)

.PHONY: $(CMAKE_BUILD_DIR)/built_executable_or_library  # to allow CMake's make check the build
$(CMAKE_BUILD_DIR)/built_executable_or_library: $(CMAKE_BUILD_DIR)/Makefile
    $(MAKE) -C $(@D) $(@F)

This should call CMake configure step when the Makefile does not exist and run make directly to build whatever you need (probably you would need to tailor called targets to your needs). CMake's generated Makefiles check the generated build system itself, so it will be reconfigured as needed.

raspy
  • 3,995
  • 1
  • 14
  • 18
  • maybe better dependency to Makefile should be "all recursively found CMakeLists.txt"? as alternative to .Phony suggested below? – kwesolowski Jun 08 '20 at 15:42
  • The only way to make sure that your subproject is up to date is to always run its Makefile. The project may require rebuild due to source code change, not necessarily CMakeLists.txt. Once Makefile is generated, always call make to ensure that everything that needs to be done is done. – raspy Jun 08 '20 at 20:52
  • Ahh, so after first generation cmake already adds all txt files to dependencies. – kwesolowski Jun 09 '20 at 14:25
1

In addition to raspy answer I would also add .PHONY to the Makefile target:

.PHONY: $(CMAKE_BUILD_DIR)/Makefile
$(CMAKE_BUILD_DIR)/Makefile: $(CMAKE_SOURCE_DIR)/CMakeLists.txt
    cmake -S $(<D) -B $(@D)

Since the file Makefile is already there, and its dependencies didn't change, nothing will be done when changing the sources unless we treat the Makefile as always out-of-date.

wic
  • 11
  • 2
  • 1
    I wouldn't. This will cause project's reconfiguration on every build, which is unnecessary. CMake's generated Makefiles do their own sanitization of build system and will reconfigure if needed on `make` invocation. The only time this rule is needed is to bootstrap when no Makefile exists yet. – raspy Jun 08 '20 at 20:55