correctly setting symbol visibility for shared libraries

I’m currently using

include(GenerateExportHeader)
generate_export_header(${THALIA_TARGET_NAME})

in order to generate <MyTarget>_EXPORT macro for managing my library symbols visibility.

By default, it resolve by default to nothing on gcc/clang, letting all the symbol to be visible by default.

I’d like to reverse the logic and make them hidden by default and so <MyTarget>_EXPORT should resolve to __attribute__ ((visibility ("default"))).

I tried:

set(CMAKE_CXX_VISIBILITY_PRESET hidden)
include(GenerateExportHeader)
generate_export_header(${THALIA_TARGET_NAME})

But <MyTarget>_EXPORT still resolves to nothing and -fvisibility=hidden is not added to the compilation flags.

What is the correct way to achieve hidden visibility on gcc/clang and have automatically the correct <MyTarget>_EXPORT macro?
Should I use also CMAKE_VISIBILITY_INLINES_HIDDEN and how?

Regards
A.

The variable CMAKE_CXX_VISIBILITY_PRESET is used to initialise the target property CXX_VISIBILITY_PRESET: in other words, the value which applies to a target is the value the variable has at the moment the target is created. Move your set(CMAKE_CXX_VISIBILITY_PRESET hidden) command before the add_library() which creates the library.

Good point: -fvisibility=hidden appeared in my compilation line. But the export macro is still empty…

update1: the macro is correctly updated on linux but not on windows (for gcc shipped with msys2).
update2: I have misread the produced header. There is no distinction between gcc and msvc on windows and it always gives define <MyTarget>_EXPORT __declspec(dllexport) or define <MyTarget>_EXPORT __declspec(dllimport) but, for gcc, __declspec is itself expanded to __attribute__ and __attibute__(dllxxport) seems the right way to set visibility on gnu compiler for windows.

Regards