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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM