C++ - 纯C语言写的代码在C++中使用

我们拿在Qt项目中加入纯C语言写的代码文件来举例

 

问题

在Qt项目中如果加入纯C语言写的代码文件后,Qt工程就会无法编译。

 

解决方法

在纯C语言写的代码文件的头文件中加入以下内容即可

#pragma once
//C++ 运行该文件时,extern C包含的内容用C语言方式连接
#ifdef __cplusplus
   extern "C"{
#endif 
 
//C代码内容所在位置
 
#ifdef __cplusplus
}
#endif 

 

 

实例

纯C语言写的代码文件为:test.h,test.c

其中test.c文件内容为:

#include "test.h"
#include <stdio.h>

int add(int a,int b)
{
    return a+b;
}

则test.h文件内容应为:

#ifndef TEST_H
#define TEST_H

//C++ 运行该文件时,extern C包含的内容用C语言方式连接
#ifdef __cplusplus
   extern "C"{
#endif 
 
#include <stdio.h>
int add();
 
#ifdef __cplusplus
}
#endif

#endif

 

posted @ 2020-07-16 14:10  Citrusliu  阅读(1160)  评论(0编辑  收藏  举报