Below is a simple CMake project. On Linux, everything compiles, and running main gives expected output. On Windows, the compilation is successful as well, main doesn't give any output, though. I can't really explain the error, but the moment I call getNumber() function from main, main no longer works. I can't even put a breakpoint there and debug it.
|-CMakeLists.txt
|-Main
|---main.cpp
|---CmakeLists.txt
|-SHLib
|---foo.h
|---foo.cpp
|---CmakeLists.txt
CMakeLists.txt:
add_subdirectory(SHLib)
add_subdirectory(Main)
Main/CMakeLists.txt:
add_executable(Main main.cpp)
target_link_libraries(Main PUBLIC SHLib)
SHLib/CMakeLists.txt
add_library(
SHLib SHARED
foo.h
foo.cpp
)
add_compile_definitions(LIBRARY_EXPORTS)
target_include_directories(SHLib PUBLIC "${PROJECT_SOURCE_DIR}")
Main/main.cpp
#include <iostream>
#include <SHLib/foo.h>
int main()
{
if (getNumber() == 7)
std::cout << "Successful linking\n";
std::cout << "End of main function\n";
}
SHLib/foo.h
#ifdef _WIN32
# ifdef LIBRARY_EXPORTS
# define LIBRARY_API __declspec( dllexport )
# else
# define LIBRARY_API __declspec( dllimport )
# endif
#else
# define LIBRARY_API
#endif
LIBRARY_API int getNumber();
SHLib/foo.cpp
#include <SHLib/foo.h>
int getNumber()
{
return 7;
}
To make it work on Windows, dll and executable has to be in the same folder. You can either copy them manually or set output directory in your top CMake file like this: set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "yours_output_directory"). This way, both executable and dll will end up in yours_output_directory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With