How to use the same name for a target and a library

We have a project that creates both a library and an executable. Moreover, we want the exec and library to have the same name.

For example:

What Windows Linux
executable foobar.exe foobar
static library foobar.lib libfoobar.a

How do I achieve this in CMake?

I get hung up with the fact that CMake’s add_executable and add_library commands automagically add the suffix, and the name has to be unique.

For example the following wouldn’t work

add_executable(foobar ......)
add_library(foobar .....)

Because the name foobar is the same and is supposed to be unique.

Right now the legacy CMake code does some creative gymnastics to rename the generated files, but I suspect there has to be an easier way than what has been historically implemented.

What is the correct, or most efficient way to do this?

You can set OUTPUT_NAME on a target to modify its basename. So:

add_library(foobar)
add_executable(foobar_exe)
set_property(TARGET foobar_exe PROPERTY OUTPUT_NAME foobar)
2 Likes

Hahahahahaha… BEAUTIFUL.

I knew there had to be an easier way than the gymnastics I saw. Thank you Ben!

1 Like