So I've been working on porting a CMake C++ to building on Windows using Visual Studio.
I've learned that, unlike Linux/g++ which exports all symbols automatically, that MSVC does not export any symbols that it is not explicitly told to do so. After some googling, I discovered CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS
and I tried that but I was still receiving linking errors (this time, my shared library wouldn't link). After some more reading, I found that CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS
actually isn't always a good idea to use, and in fact, it would be better to only export symbols you specifically need, even on Linux. (As it can allow for more optimizations and possibly faster linking times).
I worked out a much simpler "minimal" example to test out some things, and I've concluded that adding the following to the top of my header files solves the problem (at least in my minimal working example):
#if defined(_WIN64)
#define EXPORT __declspec(dllexport)
#elif defined(__linux__)
#define EXPORT __attribute__((visibility("default")))
#endif
Where I would then modify a class declaration to be:
class EXPORT MyClass {...
Doing this allowed everything to build without issue! (NOTE: while this is a template, I am explicitly instantiating it so that it only works with specific types. Because of that, the implementation for this class is in the public_class.cpp
file. I don't believe that is relevant here but I wrote it that way just to ensure this approach would work with my existing code, which has some instances of this sort of thing)
While this works, it seems extremely cumbersome to need to have this entire statement at the top of every file. Especially if, down the road, I come to realize that I need to modify something about it.
Is there a way I can streamline this statement and possibly have it in one single place in my entire project? Or is it best to have it in each individual file that contains symbols I wish to export?