2

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.
einpoklum
  • 118,144
  • 57
  • 340
  • 684

1 Answers1

2

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)
Tsyvarev
  • 60,011
  • 17
  • 110
  • 153
  • It's weird that you can't set this property per target, period. – einpoklum Jul 12 '21 at 18:12
  • As far as I understand, CMake has a **per-target** properties and **per-file** properties. But it lacks for "per-file-per-target" properties. Options `DIRECTORY` and `TARGET_DIRECTORY` for the `set_source_file_properties` are just helpers, they don't introduce additional concepts. – Tsyvarev Jul 12 '21 at 18:22