gpt4 book ai didi

c++ - Visual Studio 不区分 C header 和 C++ header

转载 作者:行者123 更新时间:2023-11-30 20:20:33 26 4
gpt4 key购买 nike

我正在使用 Visual Studio 2017-enterprise 使用 C 语言,但 C 头文件存在一个复杂的问题,因为 Visual Studio 会考虑每个头文件是一个 C++ 头文件。因此,无论扩展名是 .hpp 还是 .h,它都会将其视为 C++ header ,这会导致问题,因为我使用 C99 并且 Visual Studio 会认为 header 是 C++,因此我无法在 header 文件中使用 C 功能。

注意:当我将源文件命名为 .c 时,Visual Studio 会将其视为 C 文件,而不是 C++,并且它是好的。所以我需要对标题做同样的事情。我需要为 c 制作 .h,为 c++ 制作 .hpp 如何?

VS 2010、2013、2015 也存在此问题。

编辑::

the problem with highlighting for example if i create class in .c file visula studio will say there is error but this will not show any error if i create class in .h file even if i use extern"C"

看看这张图片: source.h现在看看这个 source.c

最佳答案

如果您从 .c 文件中#include .h 文件,则 Visual Studio 会将其编译为 C。如果您 #include 来自 .cpp 文件的 .h 文件,然后 Visual Studio 会将其编译为 C++。

在特定于 C 的 header 中执行此操作很常见:

#ifdef __cplusplus 
extern "C" {
#endif

void MyCFunction();
void MyCFunction2();

#ifdef __cplusplus
}
#endif

这允许您声明用 C 实现的函数。其他 C 源代码可以使用这些函数,C++ 源代码也可以使用这些函数。

您实际上不需要担心特定于 C++ 的 header ,因为如果您在 C 源代码中#include 它们,您只会收到编译错误。

关于c++ - Visual Studio 不区分 C header 和 C++ header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45942189/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com