3

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;
}
user680891
  • 95
  • 6
  • Did you copy the .dll file next to the executable or add the directory in which the built dll resides to the PATH? – Corristo Mar 19 '21 at 14:01
  • It indeed was the problem. I copied .dll to the executable and it works. Why it worked on Linux though? – user680891 Mar 19 '21 at 14:08
  • 1
    On Linux the full path to the .so file is included into the executable. You can probably configure CMake [output directory](https://cmake.org/cmake/help/latest/manual/cmake-buildsystem.7.html#runtime-output-artifacts) to be the same for all libs and exe's, which should help with debugging. Or you can add the lib output folder to the PATH when debugging. – rustyx Mar 19 '21 at 15:03
  • If you solved your problem, can you please describe the solution as an "answer" below and accept it? :-) – JonasVautherin Mar 23 '21 at 00:13

1 Answers1

0

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.

user680891
  • 95
  • 6