c++ - 从 C 文件调用 C++ 标准头 (cstdint)

标签 c++ c std mixing

我有一个用 C++ 编写的外部库,例如

外部.h

#ifndef OUTPUT_FROM_CPP_H
#define OUTPUT_FROM_CPP_H

#include <cstdint>
extern "C" uint8_t myCppFunction(uint8_t n);

#endif

外部.cpp

#include "external.h"
uint8_t myCppFunction(uint8_t n)
{
    return n;
}

目前我别无选择,只能在我当前的 C 项目中使用这个 C++ 库。但我的编译器告诉我

No such file or director #include <cstdint>

在我的 C 项目中使用时

ma​​in.c

#include "external.h"

int main()
{
    int a = myCppFunction(2000);

    return a;
}

我知道这是因为 cstdint 是一个 C++ 标准库,我试图通过我的 C 文件使用它。

我的问题是:

  • 有没有办法可以在我的 C 项目中使用这个 C++ 库,而无需修改我的库?
  • 如果不是,我需要在图书馆方面做什么才能使其成为可能?

最佳答案

c cstdint 中的前缀因为它实际上是从C合并而来的头文件,C中的名字是stdint.h .

您需要通过检测 __cplusplus 有条件地包含正确的 header 宏。您还需要此宏才能使用 extern "C"部分,因为这是 C++ 特定的:

#ifndef OUTPUT_FROM_CPP_H
#define OUTPUT_FROM_CPP_H

#ifdef __cplusplus
// Building with a C++ compiler
# include <cstdint>
extern "C" {
#else
// Building with a C compiler
# include <stdint.h>
#endif

uint8_t myCppFunction(uint8_t n);

#ifdef __cplusplus
}  // Match extern "C"
#endif

#endif

关于c++ - 从 C 文件调用 C++ 标准头 (cstdint),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72182138/

相关文章:

c++ - 用于构建 C++ Google Protocol Buffers 项目的 Makefile

c++ - 加油站任务变化的DP算法

c - 从文件读取最后 n 个字节时出现段错误

c++ - 每当应用程序崩溃时为其创建转储文件

r - 如何扩展 'summary' 函数以包含 sd、峰度和偏斜?

c++ - 如何正确使用互斥锁?

c++ - 为什么矩阵加法比 Eigen 中的矩阵向​​量乘法慢?

c++ - SFML Sprite 在第二次滴答时猛烈向下移动

比较 C 中的字符

c - C 中带条件的 Goto 语句