Search code examples
c++cmakeconan

File selection with conan and cmake


I have a package with 2 variants with the following directory structure

pkg
   pkg_main.h
   CMakeLists.txt
   var1
      pkg_main.cpp
   var2
      pkg_main.cpp
conanfile.py

With conan, I'm trying to define an option fileSelection with possible values var1 and var2. With cmake, I'm trying to do the selection as following: if fileSelection is set to var1, then var1/pkg_main.cpp shall be called, otherwise var2/pkg_main.cpp.

So far, I've defined the option fileSelection in conanfile.py

class PkgConan(ConanFile):
   name = "pkg"
   ...
   options = {"fileSelection : ['var1', 'var2']"}
   default_options = "fileSelection=var1"
   generators = "cmake"

   def build(self): 
      cmake = CMake(self)
      cmake.configure(source_folder="pkg")
      cmake.build()

   def package(self):
       self.copy("*.h", dst="include", src="pkg")
       self.copy("*pkg.lib", dst="lib", keep_path=False)
       self.copy("*.dll", dst="bin", keep_path=False)
       self.copy("*.so", dst="lib", keep_path=False)
       self.copy("*.dylib", dst="lib", keep_path=False)
       self.copy("*.a", dst="lib", keep_path=False)

   def package_info(self):
       self.cpp_info.libs = ["pkg"]

Now I'm struggling to update the CMakeLists.txt file to do the selection according to the value of fileSelection. Something like this:
[here's the logic, not the runnable code]

if("${fileSelection}" STREQUAL "var1") 
   add_library(pkg var1/pkg_main.cpp)
else
   add_library(pkg var2/pkg_main.cpp)
endif

?? How do I pass the fileSelection option to cmake; where and how do I implement the switch between var1 and var2 (am I going in the right direction by trying to define the switch in CMakeLists.txt)?


Solution

  • You can pass variables to cmake command line invocation driven by the cmake helper. Something like:

    options = {"fileSelection": ["var1", "var2"]}
    ...
    
    def build(self): 
       cmake = CMake(self)
       cmake.definitions["fileSelection"] = self.options.fileSelection
       cmake.configure(source_folder="pkg")
       cmake.build()
    

    That assumes that you have the CMakeLists.txt logic you describe.