在C++中导入C单头库

问题描述 投票:0回答:1

我想将 C 单头库包含到我的 C++ 代码中。 C 标头库具有与 C++ 不兼容的代码。如何实现这一目标?

main.cc

extern "C" {
  #include "single_header.h"
}

int main() {}

single_header.h

#include <stdlib.h>
void f() {
  int *p = malloc(sizeof(int));
  free(p);
}

如果我用 g++ 编译它,我会收到错误消息,它是无效的 C++ 代码,因为

extern "C"
仅与函数修饰有关。

$ g++ main.cc
In file included from main.cc:2:
single_header.h: In function ‘void f()’:
single_header.h:3:18: error: invalid conversion from ‘void*’ to ‘int*’ [-fpermissive]
    3 |   int *p = malloc(sizeof(int));
      |            ~~~~~~^~~~~~~~~~~~~
      |                  |
      |                  void*

实现这一目标的正确模式是什么?

c++ c build casting compilation
1个回答
0
投票
  1. 不要在头文件中定义函数。只放函数原型
  2. extern "C"
    只是说名称不应被破坏,它不会强制编译器将该部分编译为 C 代码。

single_header.h:

#ifndef S_H
#define S_H
extern "C" {
void f();
}
#endif

single_c_file.c:

#include <stdlib.h>
#include "single_header.h"

void f() {
  int *p = malloc(sizeof(int));
  free(p);
}

将此文件编译为 C,而不是 C++。

将所有内容链接在一起。

© www.soinside.com 2019 - 2024. All rights reserved.