c/c++单例模式类的混合编译

C/C++混合编译

难点:c++支持重载,因此g++编译后的函数名有额外信息,在gcc编译的c文件中无法识别符号,导致链接失败。

解决方案:

  1. extern “C” { }
  2. 中间层调用

extern “C”

​ 对c++文件编译时使用extern “C“ { },让编译器安装c语言的规则对其中的内容进行编译,主要解决c++中重载函数名导致符号不识别的问题。

​ 同时配合ifdef __cplusplusendif实现文件(主要是头文件)被gcc和g++编译时能够自动匹配当前编译器的语言。另一方面也是因为c语言不支持extern “C”关键字。

中间层调用

​ 由于c语言中没有类的概念,因此对于有类的cpp文件与c文件混合编译时,提供一个中间层提供类的操作接口,在c文件中调用接口实现间接操作类对象。

log案例

背景:main.c中需要调用logClass.cpp文件中的logClass类的相关成员函数,并且该类是一个单例模式。

解决方案:

文件目录

│main.c

├─include
│ interFace.h
│ logClass.h

└─src
interFace.cpp
logClass.cpp

源代码

main.c

#include "interFace.h"
#include <stdint.h>
#include <stdio.h>

int main()
{
    set_log_count(10);
    uint32_t count = get_log_count();
    printf("The conut is %d\n", count);
}

logClass.h

#ifndef LOG_CLASS_H
#define LOG_CLASS_H
#include <stdint.h>
#include <stdio.h>

#define FCA_BOOL uint16_t
#define FCA_TRUE 1
#define FCA_FALSE 0
class logClass
{
public:
    static logClass *getInstance()
    {
        static logClass m_plogClass;
        return &m_plogClass;
    }

    FCA_BOOL setLogCount(uint32_t num);
    uint32_t getLogCount();

private:
    logClass();
    logClass(const logClass &) = delete;
    logClass &operator=(const logClass &) = delete;
    ~logClass();
    uint32_t m_logCount;
    static logClass* m_plogClass;
};
#endif

logClass.cpp

#include "logClass.h"

logClass::logClass(/* args */)
{
    printf("log class construct!!!!!\n");
}

logClass::~logClass()
{
    printf("log class destruct!!\n");
}

FCA_BOOL logClass::setLogCount(uint32_t num)
{
    m_logCount = num;
    return FCA_TRUE;
}

uint32_t logClass::getLogCount()
{
    return m_logCount;
}

interFace.cpp

#include "interFace.h"
#include "logClass.h"

logClass* log = logClass::getInstance();

FCA_BOOL set_log_count(uint32_t num)
{
    FCA_BOOL ret = log->setLogCount(num);
    return ret;
}

uint32_t get_log_count()
{
    return log->getLogCount();
}

interFace.h

#ifndef INTERFACE_H
#define INTERFACE_H
#include <stdint.h>

#define FCA_BOOL uint16_t
#define FCA_TRUE 1
#define FCA_FALSE 0

#ifdef __cplusplus
extern "C"
{
#endif
FCA_BOOL set_log_count(uint32_t num);
uint32_t get_log_count();
#ifdef __cplusplus
}
#endif
#endif

CMakeLists.txt

cmake_minimum_required(VERSION 3.0)
project(MYLOGTEST CXX C)
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")  #设置c++的编译选项
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99")  #设置c的编译选项
include_directories(include)
add_executable(mylogtest main.c src/logClass.cpp src/interFace.cpp)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值