Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally add files to library in C++ project

Tags:

c++

cmake

I have a CMake C++ project that consist of a library and multiple executable applications. The library contains many files and conditionally depending on whether the user wants to have GPU acceleration the list of files in the library should be different e.g.

if (GPU_ACCELERATED) 
   add_library(my_library
      file1.h
      file1.cc
      gpu_file2.h
      gpu_file2.cc
   )
else()
   add_library(my_library
      file1.h
      file1.cc
   )
endif()

This is one way of doing it but the problem is that I have a massive number of files and not just file1.h file1.cc therefore I'd very strongly prefer to avoid duplicating the file listing like that. I would rather like something like this to work (but doesn't) e.g.

add_library(my_library
    file1.h
    file1.cc
    if (GPU_ACCELERATED) 
       gpu_file2.h
       gpu_file2.cc
    endif()
 )
like image 523
SkyWalker Avatar asked Jan 07 '14 09:01

SkyWalker


People also ask

How to add an external C++ library to your project?

How to Add an External C++ Library to Your Project Using the CodeLite IDE Step 1: Go to the website of the library. For example, for the linear algebra library, Eigen, you go to this page: Eigen... Step 2: Download the zip file that contains all the code. Step 3: Unzip the zip file to your computer. ...

How do I add additional directories to a C++ project?

I’ll name this file main.cpp. Step 8: Click on the Project tab at the top and go to Additional Include Directories. Project -> Properties -> C/C++ -> General (you can find it by expanding the little triangle next to C/C++) -> Additional Include Directories Step 9: Click the blank next to “Additional Include Directories”.

How to install C++ libraries on Windows?

Note that this process will be different if you are using another IDE for C++, but the two basic steps are the same for all IDEs: Step 1: Go to the website of the library. Step 2: Download the zip file that contains all the code. Step 3: Unzip the zip file to your computer.

What are libraries in C++ and how to use them?

Libraries in C++ are collections of code that someone else wrote. They prevent you from having to reinvent the wheel when you need to implement some desired functionality. You can think of libraries as a plugin or add-on that gives you more functionality. For example, I wanted to write a program that is able to multiply two matrices together.


1 Answers

Use the set command to create and update CMake variables:

set(my_SOURCES file1.h file1.cc)

if (GPU_ACCELERATED)
    set(my_SOURCES ${my_SOURCES} gpu_file2.h gpu_file2.cc)
endif()

add_library(my_library ${my_SOURCES})

This will define a my_SOURCES variable, if GPU_ACCELERATED is true it will update it. Then create your library from the content of the variable.

like image 147
Guillaume Avatar answered Sep 25 '22 03:09

Guillaume