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?
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.
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.