Search code examples
c++ccmakebuildcross-language

How can I have CMake compile the same input file in two different languages?


I have a file named foo.bar. I want to compile it once as a C++ file, into a mycpplib library target, and once as a C file, into a myclib target; and I want to do it in the same build, with the same CMakeLists.txt.

Now, I know I can arbitrarily set a source file's associated language, like so:

set_source_files_properties(foo.bar PROPERTIES LANGUAGE C)

but this doesn't look like it'll help in my case. Is there something I can do at the CMake level?

Notes:

  • Related question: The single-arbitrary-language case.
  • There are non-CMake solutions to this, e.g. duplicating the file; using a symlink with a different name; having a file with #include "otherfile" as its contents etc.

Solution

  • You could create library targets mycpplib and myclib in the different directories (in the different CMakeLists.txt). That way you may call set_source_files_properties in the directory where mycpplib library is created, and that call won't affect on myclib.

    There are also DIRECTORY and TARGET_DIRECTORY options for command set_source_files_properties, which could affect on the directory where the property will be visible:

    # In 'c/CMakeLists.txt`
    # add_library(myclib ${CMAKE_SOURCE_DIR}/foo.bar)
    
    # In 'cpp/CMakeLists.txt`
    # add_library(mycpplib ${CMAKE_SOURCE_DIR}/foo.bar)
    
    # In CMakeLists.txt
    add_subdirectory(c)
    add_subdirectory(cpp)
    set_source_file_properties(foo.bar TARGET_DIRECTORY myclib
      PROPERTIES LANGUAGE C)
    set_source_file_properties(foo.bar TARGET_DIRECTORY mycpplib
      PROPERTIES LANGUAGE CXX)