Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linking a shared library to an executable using CMAKE

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;
}
like image 572
user680891 Avatar asked Sep 23 '26 06:09

user680891


1 Answers

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.

like image 83
user680891 Avatar answered Sep 24 '26 22:09

user680891



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!