How to create a static library that use JUCE in official CMake?

Note that it isn’t officially supported to create static libs from the juce-modules (see here).

Having said that- this could work for you:

add_library (juce_staticlib)
target_link_libraries (juce_staticlib PRIVATE juce::juce_core)

Note that its necessary to use private linking here, otherwise the juce-modules would be recompiled when consuming the juce_staticlib, since they are interface targets. On the other hand, compiler flags and include directories ect. are not propagated correctly when using private linkage.

We’ve faced this problems when trying to link a plugin-shared-code-target against a console application for unit testing. We’re using some dirty trickery to work around this:

# add console app
add_executable (unit_test_target)

# use the same C++ standard
get_target_property (PLUGIN_TARGET_CXX_STANDARD plugin_target CXX_STANDARD)
set_target_properties (unit_test_target PROPERTIES CXX_STANDARD ${PLUGIN_TARGET_CXX_STANDARD})

# use the same include directories
target_include_directories (unit_test_target PRIVATE $<TARGET_PROPERTY:plugin_target,INCLUDE_DIRECTORIES>)

# use the same compiler flags
target_compile_options (unit_test_target PRIVATE $<TARGET_PROPERTY:plugin_target,COMPILE_OPTIONS>)

# use the same macros
target_compile_definitions (unit_test_target PRIVATE $<TARGET_PROPERTY:plugin_target,COMPILE_DEFINITIONS>)

This works fine in our case, but I’m not sure whether this will produce the correct results in every situation.