I've been building C and C++ projects in unix environments using CMake. However, I want to also start compiling in MSVC and I'm trying to get my head around the cmake documentation but I'm getting stuck. I keep getting the following message when I try to build.
LINK : fatal error LNK1104: cannot open file 'Debug\MyLibrary.lib' [C:\sandbox\projects\cpp\DummyChelloWorld\build\ma inProgram.vcxproj]
Can you tell me what I'm doing wrong?
CMakeLists.txt
cmake_minimum_required(VERSION 3.4)
project(helloWorld)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
include(GenerateExportHeader)
ADD_LIBRARY(MyLibrary SHARED myShared.cpp)
set(SOURCE_FILES main.cpp)
GENERATE_EXPORT_HEADER( MyLibrary
BASE_NAME MyLibrary
EXPORT_MACRO_NAME MyLibrary_EXPORT
EXPORT_FILE_NAME ${CMAKE_BINARY_DIR}/MyLibrary_Export.h
STATIC_DEFINE MyLibrary_BUILT_AS_STATIC
)
add_executable(mainProgram ${SOURCE_FILES})
TARGET_LINK_LIBRARIES(mainProgram MyLibrary)
TARGET_INCLUDE_DIRECTORIES(mainProgram PUBLIC exports)
main.cpp
#include "myShared.h"
int main() {
sayHI();
return 0;
}
myShared.cpp
#include <iostream>
#include "myShared.h"
using namespace std;
void sayHI() {
cout << "Hello World lib" << endl;
}
myShared.h
#ifndef HELLOWORLD_HELLO_H
#define HELLOWORLD_HELLO_H
void sayHI();
#endif //HELLOWORLD_HELLO_H
Turning my comment into an answer
For CMake Version >= 3.4
Just use CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS
:
cmake_minimum_required(VERSION 3.4)
project(helloWorld)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS 1)
add_library(MyLibrary SHARED myShared.cpp)
set(SOURCE_FILES main.cpp)
add_executable(mainProgram ${SOURCE_FILES})
TARGET_LINK_LIBRARIES(mainProgram MyLibrary)
For CMake Version < 3.4
You need to declare your functions/symbols as exported. So in your case, you have to modify the following files:
myShared.h
#ifndef HELLOWORLD_HELLO_H
#define HELLOWORLD_HELLO_H
#include "MyLibrary_Export.h"
void MyLibrary_EXPORT sayHI();
#endif //HELLOWORLD_HELLO_H
CMakeLists.txt
cmake_minimum_required(VERSION 3.4)
project(helloWorld)
set(CMAKE_CXX_STANDARD 11)
include(GenerateExportHeader)
add_library(
MyLibrary
SHARED
myShared.cpp
myShared.h
MyLibrary_Export.h
)
GENERATE_EXPORT_HEADER(
MyLibrary
BASE_NAME MyLibrary
EXPORT_MACRO_NAME MyLibrary_EXPORT
EXPORT_FILE_NAME MyLibrary_Export.h
STATIC_DEFINE MyLibrary_BUILT_AS_STATIC
)
target_include_directories(MyLibrary PUBLIC "${CMAKE_CURRENT_BINARY_DIR}")
set(SOURCE_FILES main.cpp)
add_executable(mainProgram ${SOURCE_FILES})
TARGET_LINK_LIBRARIES(mainProgram MyLibrary)
I've
MyLibrary_EXPORT
to your function declarationCMAKE_CURRENT_BINARY_DIR
to the shared libraries include paths (to point to the generated export definitions header) CMAKE_CXX_STANDARD
definition.Alternative
References
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