Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an include once command for cmake files?

Tags:

cmake

Does anyone know a simple way to apply the "include once" pattern in CMake files? In C/C++ it used to require a #ifdef / #endif pair in the beginning and end of the header file until #pragma once became common. Of course, it's possible to do the same in CMake, but I thought it'd be nice if it didn't require an explicit conditional statement.

Re-edition: It seems that the return() command should do it. And I'd define a macro like this:

macro(include_once)
  if (INCLUDED_${CMAKE_CURRENT_LIST_FILE})
    return()
  endif()
  set(INCLUDED_${CMAKE_CURRENT_LIST_FILE} true)
endmacro()

Use the macro in the beginning of your file, without any arguments. Because it's a macro, the return is from the include command for the file, not from the macro itself.

Notice that the created variable has an odd name, but CMake seems to accept this.

like image 234
Ofri Sadowsky Avatar asked Jun 20 '17 06:06

Ofri Sadowsky


People also ask

Where does CMake look for include files?

cmake is searched first in CMAKE_MODULE_PATH , then in the CMake module directory. There is one exception to this: if the file which calls include() is located itself in the CMake builtin module directory, then first the CMake builtin module directory is searched and CMAKE_MODULE_PATH afterwards.

How do I include a .h file in CMake?

To include headers in CMake targets, use the command target_include_directories(...) . Depending on the purpose of the included directories, you will need to define the scope specifier – either PUBLIC , PRIVATE or INTERFACE .

How do I edit a CMake file?

CMakeLists files can be edited in almost any text editor. Some editors, such as Notepad++, come with CMake syntax highlighting and indentation support built-in.


1 Answers

I used to use the logic that others have suggested as the solution. Then I learned that cmake has this functionality built in.

Take a look at include_guard(). I believe this will do what you want.

like image 115
John Rocha Avatar answered Oct 28 '22 13:10

John Rocha