我可以使用 extern "C" { c 的头文件 }

can I use extern "C" { headerfile of c }

本文关键字:文件 可以使 extern 我可以      更新时间:2023-10-16

而不是在" extern "C" {}"中编写每个函数,我可以在该块中写入整个头文件吗?

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

我已经试过了,但它根本不起作用,为什么它不起作用?如果我们必须在 C++ 项目中使用 100 个 C 函数,我们是否需要在外部块,还有其他简单的方法吗?

前任:

extern "C"
{
 void fun1();
 void fun2();
 void fun3();
 void fun4();
 void fun5();
 .
 .
 .
 .
 fun100();
}

有没有其他简单的方法,比如extern "C" { myCfunctions.h } ???

#include只是在#include的位置包含指定的标头。它是否有效取决于"myCfile.h"包含的内容。特别是,在这样的上下文中包含任何标准库标头都是无效的,并且很可能会破坏常用的实现。

处理此问题的常用方法是使标头本身可以安全地从C++使用。仅 C 标头可能包含

#ifndef H_MYCFILE
#define H_MYCFILE
#include <stddef.h>
void mycfunc1(void);
void mycfunc2(int i);
void mycfunc3(size_t s);
#endif

对此进行调整以使其可以从C++安全使用:

#ifndef H_MYCFILE
#define H_MYCFILE
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
void mycfunc1(void);
void mycfunc2(int i);
void mycfunc3(size_t s);
#ifdef __cplusplus
}
#endif
#endif

使用这样的标头,您将无法安全地将整个标头放入extern "C"块中。但是,该标头本身可以确保#include <stddef.h>放在extern "C"块中,但仍将所有函数声明放在单个extern "C"块中,避免为每个函数声明重复它。

你做错了什么。

因为

extern "C" { myCfunctions.h }

应该工作。请参阅下面的示例程序。


让我们通过示例代码。

测试1.c

#include<stdio.h>
void ctest1(int *i)
{
   printf("This is from ctest1n"); // output of this is missing
   *i=15;
   return;
}

ctest2.c

#include<stdio.h>
void ctest2(int *i)
{
   printf("This is from ctest2n"); // output of this is missing
   *i=100;
   return;
}

Ctest.h

void ctest1(int *);
void ctest2(int *);

现在让我们从中制作 c 库

gcc -Wall -c ctest1.c ctest2.c
ar -cvq libctest.a ctest1.o ctest2.o

现在让我们制作基于cpp的文件,它将使用此c apis进度.cpp

#include <iostream>
extern "C" {
#include"ctest.h"
}
using namespace std;
int main()
{
  int x;
  ctest1(&x);
  std::cout << "Value is" << x;
  ctest2(&x);
  std::cout << "Value is" << x;
}

现在让我们用 C 库编译这个 c++ 程序

g++ prog.cpp libctest.a

输出为 :值是15值是100