Search code examples
pythonc++visual-studio-2012cmakeextending

Building dynamic library from Visual studio files


I am writing a C++ module for Python3. To make Python working with it, I have to build C++ source into dynamic library (one of the requirements is windows-compatibility).

The source code is correctly compiled and linked with Cmake (my cmake generator is Visual Studio 12 2013 Win64). But then I have to build .dll file from Cmake files. The list of Cmake files if here: enter image description here

Note, there isn't Makefile in this list!

How can I build .dll from this files? I tried MinGW and GNUwin32, but trey weren't working.

My CMakeLists.txt is below:

cmake_minimum_required(VERSION 3.2)
set(CMAKE_VERBOSE_MAKEFILES on)
project(Proj)
set(SOURCE_FILES repeating_count.cpp)

set(BUILD_SHARED_LIBS ON)

set(CMAKE_VERBOSE_MAKEFILE on)
find_package(PythonLibs 3.4 REQUIRED)
include_directories(${PYTHON_INCLUDE_DIRS})
python_add_module(repeating_count repeating_count.cpp)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
add_executable(Proj ${SOURCE_FILES})
target_link_libraries(Proj ${PYTHON_LIBRARIES})

Solution

  • Given that you're using CMake, you can achieve this by adding

    set(BUILD_SHARED_LIBS ON)
    

    before you define your libraries (perhaps, simply in the beginning of your CMakeLists.txt). See documentation of this flag here.

    Alternatively, you can directly force a library to be shared by adding a SHARED flag to you add_library:

    add_library(myLibrary SHARED ${sources})
    

    See documentation regarding this here.

    Your modified CMakeLists should then look like

    cmake_minimum_required(VERSION 3.2)
    
    set(CMAKE_VERBOSE_MAKEFILES on)
    project(Proj)
    set(SOURCE_FILES repeating_count.cpp)
    
    set(BUILD_SHARED_LIBS ON)
    
    # Find PythonLibs
    find_package(PythonLibs 3.4 REQUIRED)
    include_directories(${PYTHON_INCLUDE_DIRS})
    
    # This will create the Proj.dll
    add_library(Proj ${SOURCE_FILES})
    target_link_libraries(Proj ${PYTHON_LIBRARIES})
    

    Regarding the -std=c++11 flag - you don't need that for MSVS generator. If you're really interested in the correct way to ensure c++XX flags are enabled for any generator, take a look at target_compile_features.