c++ - IAR does not correctly compile C++ file with Auto (extension-based) option enabled
问题描述
This may be a bit of a long shot...
I have a C project and want to include a C++ file however I am getting an error with the following code:
//GPIO_CPP.cpp
class GPIO
{
public:
uint32_t Port;
uint32_t Pin;
};
#ifndef __cplusplus
#error Enable CPP compilation
#endif
This inluded in my main.c as follows:
//main.c
#include "GPIO_CPP.cpp"
Error:
Error[Pe020]: identifier "class" is undefined
I have also tried putting this in a header file with .h and .hpp extensions with the same behaviour.
I've placed a compiler check:
#ifndef __cplusplus
#error Enable CPP compilation
#endif
which is firing.
My compiler options:
解决方案
假设您尝试在 C 项目中包含 C++ 模块,最好的方法是:
gpio.h
#ifndef GPIO_H
#define GPIO_H
// Types accessible to C and C++ modules
struct GPIO
{
uint32_t Port;
uint32_t Pin;
};
// Functions accessible to C and C++ modules.
// Use extern "C" only when included to C++ file.
#ifdef __cplusplus
extern "C" {
#endif
void foo(uint32_t x);
#ifdef __cplusplus
}
#endif
// Functions accessible to C++ modules only.
// These functions not visible if included to C file.
#ifdef __cplusplus
void bar(uint32_t x);
#endif
#endif
gpio.cpp
#include "gpio.h"
// extern "C" declaration must be visible to this definition to compile with C compatible signature
void foo(uint32_t x) {
// It's OK to call C++ functions from C compatible functions,
// because this is C++ compilation unit.
bar(x);
}
// This function can be called only from C++ modules
void bar(uint32_t x) {
// It's OK to call C compatible functions from C++ functions
foo(x);
}
主程序
#include "gpio.h"
// Use only C compatible types (struct GPIO) and functions (foo) here
int main(void) {
foo(1); // ok, because of extern "C"
bar(1); // invalid because this is C file
}
main.c
将和添加gpio.cpp
到您的项目树中,并确保将语言设置设置为Auto
.
推荐阅读
- html - Angular 5:无法将 MatDialog 的位置居中或设置样式
- python - 计算 .txt 中的单词,然后将结果写入相同的 .txt
- c# - 打印在标签上的数据库下拉列表值
- jetty - Embedded Jetty:注册 ServletRequestListener 的 ServletContextListener
- common-lisp - Clisp :选择给定长度的子列表
- azure - Sharepoint REST api - 领域不是当前服务命名空间错误 50169 的配置领域
- angular - 无论您单击何处,Highchart 工具提示都会显示相同的值
- angular - 角 ngFor。如何有条件地显示标题?
- pip - conda activate env 不适用于 azure 批处理节点任务
- javascript - 使变量在其他函数中可用