Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile a single file under CMake project?

Tags:

I'm developing a C++ project which is going to be enclosed on a bigger one.

I've seen that on the bigger project (is a Qt application and it's being generated from qmake) I am able to compile a single file from the linux command line, just entering the relative path to the specific file as an argument to make.

On the other hand, I'm using CMake for my own project. When I modify some code for a compilation unit and I have to modify its header file, I have to wait a long time to compile its dependencies and then its own source file. But there are some situations in which I would prefer to check whether the source code in the *.cc file is compilable without errors.

Is there a way to generate a Makefile from CMake the way qmake does this? Switching to qmake is not an option anymore.

like image 529
pacorrop Avatar asked Jul 08 '16 16:07

pacorrop


People also ask

How do I compile a project using CMake?

Run the cmake executable or the cmake-gui to configure the project and then build it with your chosen build tool. Run the install step by using the install option of the cmake command (introduced in 3.15, older versions of CMake must use make install ) from the command line, or build the INSTALL target from an IDE.

How do you compile a file?

To compile all open files, click on the "Compile" button. If you want to just compile a specific file, right click on its name on the left listing of files, and select Compile Current Document. Once the compile is completed, the results are displayed on the Compiler Output tab at the bottom of the screen.


2 Answers

You do not have to add extra custom targets to your CMake scripts, as the Makefiles generated by CMake already contain .o targets for each .cc file. E.g. if you have a source file called mySourceFile.cc, there will be a Makefile in your build directory that defines a target called <Some Path>/mySourceFile.cc.o. If you cd into your build directory, you can use grep or ack-grep to locate the Makefile that defines this target, then cd into that Makefile's directory and build it.

E.g. suppose the command ack-grep mySourceFile.cc.o prints something like:

foo/bar/Makefile
119:x/y/z/mySourceFile.o: x/y/z/mySourceFile.cc.o
123:x/y/z/mySourceFile.cc.o:
124:    # recipe for building target

Then you can build mySourceFile.cc.o by doing:

cd foo/bar && make x/y/z/mySourceFile.cc.o
like image 161
Ose Avatar answered Sep 21 '22 13:09

Ose


CMake doesn't have a generic built-in way of doing this (it's an open issue), but if you're using the Ninja generator, you can can use a special Ninja syntax for building just the direct outputs of a given source file. For example, to compile just foo.o you would use:

ninja /path/to/foo.cpp^
like image 19
nocnokneo Avatar answered Sep 20 '22 13:09

nocnokneo