CMake link shared library on Windows

前端 未结 2 782
刺人心
刺人心 2020-12-03 01:48

There are three files, (m.c,m.h, and **main.c*).

File m.h

// m.h
int m();

File m.c

相关标签:
2条回答
  • 2020-12-03 02:22

    Using WINDOWS_EXPORT_ALL_SYMBOLS might help. See an introductory article for details. In short, invoke CMake like this:

    cmake -DCMAKE_WINDOWS_EXPORT_ALL_SYMBOLS=TRUE -DBUILD_SHARED_LIBS=TRUE
    
    0 讨论(0)
  • 2020-12-03 02:27

    There are differences between dynamic library linking on different platforms which also needs some additional code. The good news is, that CMake can help you with this. I found the following blog post by Gernot Klingler very useful:

    • Creating and using shared libraries with different compilers on different operating systems

    In short you need some "export prefix" defined for whatever is declared in m.h. Otherwise the build process will not generate an "import library" for statically linking named m.lib (see also CMAKE_IMPORT_LIBRARY_SUFFIX).

    Here is your code with the modifications needed:

    m.h

    #include "m_exports.h"
    
    int M_EXPORTS m();
    

    m.c

    #include "m.h"
    #include <stdio.h>
    
    int m(){
        printf("Hello,m!\n");
        return 0;
    }
    

    CMakeLists.txt

    cmake_minimum_required(VERSION 3.0)
    
    include(GenerateExportHeader)
    
    PROJECT("app1")
    
    INCLUDE_DIRECTORIES("${CMAKE_CURRENT_BINARY_DIR}")
    ADD_LIBRARY(m SHARED m.c m.h m_exports.h)
    GENERATE_EXPORT_HEADER(m           
        BASE_NAME m
        EXPORT_MACRO_NAME M_EXPORTS
        EXPORT_FILE_NAME m_exports.h
        STATIC_DEFINE SHARED_EXPORTS_BUILT_AS_STATIC)
    
    ADD_EXECUTABLE(myexe main.c)
    TARGET_LINK_LIBRARIES(myexe m)
    

    Additional References

    • GenerateExportHeader macro
    • cmake and GenerateExportHeader
    • How do I get CMake to create a dll and its matching lib file?
    • MSDN: Walkthrough: Creating and Using a Dynamic Link Library (C++)
    0 讨论(0)
提交回复
热议问题