c++导出动态库

一、c++风格

DllExport.h

#pragma once
#include 


#ifdef API_CTRL_EXPORT
    #ifdef _WIN32
        #define API_CTRL __declspec(dllexport)
    #else
        #define API_CTRL __attribute__((visibility("default")))
    #endif
#else
    #ifdef _WIN32
        #define API_CTRL __declspec(dllimport)
    #else
        #define API_CTRL 
    #endif
#endif



namespace API_C_PLUS {
class API_CTRL ApiTest
{
public:
    void DoTest();
    std::string GetData();
};

}

DllEXport.cpp

#define API_CTRL_EXPORT
#include "DllExport.h"


namespace API_C_PLUS {
void ApiTest::DoTest()
{
    printf("This is a dll export test\n");
}

std::string ApiTest::GetData()
{
    return std::string("Data from dll import");
}

}

二、c风格

CApiExport.h

#pragma once
#include 


#ifdef API_CTRL_EXPORT_C
    #ifdef _WIN32
        #define API_CTRL_C __declspec(dllexport)
    #else
        #define API_CTRL_C __attribute__((visibility("default")))
    #endif
#else
    #ifdef _WIN32
        #define API_CTRL_C __declspec(dllimport)
    #else
        #define API_CTRL_C 
    #endif
#endif



namespace API_C{
API_CTRL_C void DoTest();

API_CTRL_C std::string GetData();
}


CApiExport.cpp

#define API_CTRL_EXPORT_C
#include "CApiExport.h"


namespace API_C {
void DoTest()
{
    printf("This is a dll export test\n");
}

std::string GetData()
{
    return std::string("Data from dll import");
}

}

三、测试

#include 
#include "../DllEXport/DllExport.h"
#include "../DllEXport/CApiExport.h"


// set lib path
#pragma comment(lib, "../Debug/DllEXport.lib")
int main()
{
    std::cout << "-------------Test c++ class export-------------\n";
    // test c++ class api
    {
        API_C_PLUS::ApiTest objTest;
        objTest.DoTest();

        std::string strData(objTest.GetData());
        std::cout << "Data: " << strData << "\n";
    }

    std::cout << "\n\n-------------Test c++ class export-------------\n";
    // test c api
    {
        API_C::DoTest();
        std::string strData(API_C::GetData());
        std::cout << "Data: " << strData << "\n";
    }

    getchar();
    return 0;
}

你可能感兴趣的:(c++,开发语言)