[C++][cmake]C++调用C语言

在软件开发中,有时候需要在C++中调用C语言的代码,核心的解决办法就是添加extern "C",为了完整的演示调用过程,这里将采用CMakeLists.txt方式编译运行一个完整代码。

// 在xxx.h文件中
#ifdef __cplusplus
extern "C" {
#endif
void test(int a); // 添加C语言的函数声明 
#ifdef __cplusplus
}

代码目录结构

├── build  编译输出的文件夹
├── mk.sh  编译脚本
└── test   源代码
    ├── CMakeLists.txt
    ├── main.cpp
    ├── test.c
    └── test.h

CMakeLists.txt文件

# 版本cmake最低要求
cmake_minimum_required(VERSION 2.8)

# 项目名称
project(test)

# 添加所有的cpp文件
FILE(GLOB SRC_FILE_CPP ${PROJECT_SOURCE_DIR}/*.cpp)

# 添加所有的c文件
FILE(GLOB SRC_FILE_C ${PROJECT_SOURCE_DIR}/*.c)

# 添加头文件路径
include_directories(
  ${PROJECT_SOURCE_DIR}/
)

# 可执行文件
add_executable(${PROJECT_NAME} ${SRC_FILE_CPP} ${SRC_FILE_C})

代码

  • main.cpp
#include <iostream>
#include <test.h>

using namespace std;

int main() {
    cout << "[main.cpp] runing" << endl;
    test(123);
    cout << "[main.cpp] ------" << endl;

    return 0;
}
  • test.c
#include "test.h"
#include <stdio.h>
void test(int a) 
{
    printf("[test.c] test a = %d
", a);
}
  • test.h
#ifndef _CALC_H_
#define _CALC_H_

#ifdef __cplusplus
extern "C" {
#endif

void test(int a);  

#ifdef __cplusplus
}
#endif

#endif

编译脚本

  • mk.sh
# 版本cmake最低要求
cmake_minimum_required(VERSION 2.8)

# 项目名称
project(test)

# 添加所有的cpp文件
FILE(GLOB SRC_FILE_CPP ${PROJECT_SOURCE_DIR}/*.cpp)

# 添加所有的c文件
FILE(GLOB SRC_FILE_C ${PROJECT_SOURCE_DIR}/*.c)

# 添加头文件路径
include_directories(
  ${PROJECT_SOURCE_DIR}/
)

# 可执行文件
add_executable(${PROJECT_NAME} ${SRC_FILE_CPP} ${SRC_FILE_C})

运行结果

原文地址:https://www.cnblogs.com/zou107/p/15390001.html