Generating preprocessed sources in CMake projects
Hi,
It appears you can use CMake to quickly generate preprocessed source of your chosen .cpp
file without modifying the CMakeLists.txt
project file. This trick works only when your generator is make
-- meaning, it won't work with the ninja
builder.
But still, if you're using make
as your generator, try the following.
First, create a sample source code (~/dev/project/test.cpp
):
#include <iostream>
using namespace std;
int main() {
cout << "hello world\n";
return 0;
}
Then, create your CMakeLists.txt
file with nothing but just a standard set of commands (~/dev/project/CMakeLists.txt
):
cmake_minimum_required(VERSION 3.5)
project(cpptest)
add_executable(cpptest test.cpp)
Next step is to create your build directory:
$ cd ~/dev/project
$ ls
CMakeLists.txt test.cpp
$ mkdir build && cd build
$ cmake ..
-- The C compiler identification is GNU 8.2.1
-- The CXX compiler identification is GNU 8.2.1
-- Check for working C compiler: /bin/cc
-- Check for working C compiler: /bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /bin/c++
-- Check for working CXX compiler: /bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /home/antek/dev/project/build
Now you can issue make
in order to build the project, but also you can do:
$ make test.cpp.i
Preprocessing CXX source to CMakeFiles/cpptest.dir/test.cpp.i
This way CMake will use proper build flags, include directories, proper dependency management, etc, when generating the preprocessed source file. This should work in your own CMake-based project without any modifications.
G.