What's the idiomatic way to compile the same file twice, with different languages?

580 Views Asked by At

I have a source file which is valid in (at least) two languages. Say, C and C++ or C and CUDA.

I want to compile this file in both languages, each time into a different library. What's the idiomatic way of doing this in recent versions of CMake?

Notes:

2

There are 2 best solutions below

0
Peter On

This elaborates on @KamilCuk's suggestion in a comment on the OP, written before I noticed the comment.

The LANGUAGE property is set on the source file itself, which is the core of your question. The documentation for this property describes it being visible in the scope of the directory where it is set. That means that one way to have different languages is to set the property in two different directories. For example:

src/
  CMakeLists.txt
  common/
    main.c
  app1/
    CMakeLists.txt
  app2/
    CMakeLists.txt

src/CMakeLists.txt:

add_subdirectory(app1)
add_subdirectory(app2)

app1/CMakeLists.txt:

set_property(SOURCE ../common/main.c PROPERTY LANGUAGE CXX)
add_executable(app1 ../common/main.c)

app2/CMakeLists.txt:

set_property(SOURCE ../common/main.c PROPERTY LANGUAGE C)
add_executable(app2 ../common/main.c)

This will build main.c into two different targets, with two different LANGUAGE settings.

The docs also hint at being able to set the property explicitly against other directory scopes including binary directories. I was hoping this would help make the job simpler, but I can't get it to work.

0
einpoklum On

Since, indeed, LANGUAGE is a per-file property, I believe what should happen - and would allow for a proper idiom here - is to have a binary relation of language-to-use for pairs of (target, source file).

I've suggested this to KitWare in an issue report (gitlab.kitware.com).