C/C++教程

C语言包装C++对外提供接口(使用CMake工具)

本文主要是介绍C语言包装C++对外提供接口(使用CMake工具),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

CMakeLists.txt

cmake_minimum_required(VERSION 3.13)
cmake_minimum_required(VERSION 3.13)

#项目名称
project(cwrapcpp)

add_library(cwrapcpp SHARED  wrap1.cpp)
#
find_package(Qt5 COMPONENTS Widgets Core Gui Charts HINTS "D:\\Qt\\Qt5.9.7\\5.9.7\\msvc2017_64\\lib\\cmake")
#
include(GenerateExportHeader)
generate_export_header(cwrapcpp PREFIX_NAME C_)
#
target_compile_definitions(cwrapcpp PRIVATE cwrapcpp_EXPORTS)
target_include_directories(cwrapcpp PRIVATE ${CMAKE_BINARY_DIR})
target_link_libraries(cwrapcpp PRIVATE Qt5::Widgets Qt5::Gui Qt5::Core Qt5::Charts)

add_compile_options("<<CXX_COMPILER_ID:MSVC>:/source-charset:utf-8>")
add_compile_options("<<C_COMPILER_ID:MSVC>:/source-charset:utf-8>")

# set_property(SOURCE wrap1.cppsry PROPERTY LANGUAGE CXX)
#
install(TARGETS cwrapcpp DESTINATION ${CMAKE_BINARY_DIR}/install)
install(FILES ${CMAKE_BINARY_DIR}/cwrapcpp_export.h wrap.h  DESTINATION ${CMAKE_BINARY_DIR}/install)

cwrapcpp_export.h(CMake自动生成)

#ifndef C_CWRAPCPP_EXPORT_H
#define C_CWRAPCPP_EXPORT_H

#ifdef C_CWRAPCPP_STATIC_DEFINE
#  define C_CWRAPCPP_EXPORT
#  define C_CWRAPCPP_NO_EXPORT
#else
#  ifndef C_CWRAPCPP_EXPORT
#    ifdef cwrapcpp_EXPORTS
        /* We are building this library */
#      define C_CWRAPCPP_EXPORT __declspec(dllexport)
#    else
        /* We are using this library */
#      define C_CWRAPCPP_EXPORT __declspec(dllimport)
#    endif
#  endif

#  ifndef C_CWRAPCPP_NO_EXPORT
#    define C_CWRAPCPP_NO_EXPORT 
#  endif
#endif

#ifndef C_CWRAPCPP_DEPRECATED
#  define C_CWRAPCPP_DEPRECATED __declspec(deprecated)
#endif

#ifndef C_CWRAPCPP_DEPRECATED_EXPORT
#  define C_CWRAPCPP_DEPRECATED_EXPORT C_CWRAPCPP_EXPORT C_CWRAPCPP_DEPRECATED
#endif

#ifndef C_CWRAPCPP_DEPRECATED_NO_EXPORT
#  define C_CWRAPCPP_DEPRECATED_NO_EXPORT C_CWRAPCPP_NO_EXPORT C_CWRAPCPP_DEPRECATED
#endif

#if 0 /* DEFINE_NO_DEPRECATED */
#  ifndef C_CWRAPCPP_NO_DEPRECATED
#    define C_CWRAPCPP_NO_DEPRECATED
#  endif
#endif

#endif /* C_CWRAPCPP_EXPORT_H */

wrap.h

#ifndef __WRAP_H__
#define __WRAP_H__

#include "cwrapcpp_export.h"
//错误写法
//#define extern "C" {
#ifdef __cplusplus
extern "C" {
#endif
 C_CWRAPCPP_EXPORT  void qplot(int);
 C_CWRAPCPP_EXPORT  void qplotstr(char*);

#ifdef __cplusplus
}
#endif

#endif

wrap1.cpp

#include "wrap1.h"
#include <iostream>
#include "wrap.h"
#include <QApplication>
#include <QWidget>
#include <QLabel>

//构造函数
Ca::Ca(int a){
    std::cout<<"Ca get a num"<<a<<"\n";
}

//
void qplot(int v){
    int argc = 0;
    char *argv[]={nullptr};
    QApplication app(argc,argv);
    QWidget widget;
    Ca a(v);
    widget.show();
    app.exec();
}


//
void qplotstr(char* v){
    std::cout<<"in qplotstr get "<<v<<std::endl;    
}

wrap1.h

#pragma once
class Ca{
    public:
    Ca(int);
};
这篇关于C语言包装C++对外提供接口(使用CMake工具)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!