Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 759
einpoklum Avatar asked Dec 16 '25 14:12

einpoklum


1 Answers

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_files_properties(foo.bar TARGET_DIRECTORY myclib
  PROPERTIES LANGUAGE C)
set_source_files_properties(foo.bar TARGET_DIRECTORY mycpplib
  PROPERTIES LANGUAGE CXX)
like image 196
Tsyvarev Avatar answered Dec 19 '25 03:12

Tsyvarev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!