我可以使用 extern "C" { c 的头文件 }
can I use extern "C" { headerfile of c }
而不是在" 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
相关文章:
- 使用 fopen 打开 .pak 文件并使该文件应用于 const 无符号字符* (C++)
- 什么文件可以修改 atom 的C++语法?
- 如何格式化我的文本文件以使其不会一遍又一遍地重复同一行?
- 头文件可以在主类中运行.这怎么可能?
- 一个C头文件可以被认为是一个接口吗
- 保存文件并使控制台不关闭:Visual Studio 2019
- G++ 在生成文件中使用时停止工作
- 是否可以使C++类成为Objc类的委托
- 是否可以使一个类成为两个不同层次结构的子类?
- 是否有编译器标志可以使较新的 gcc 版本像旧版本一样构建
- MEX 文件可以使用 -fsanitize=address 运行吗?
- 在头文件中使用时无法识别结构
- C 可以使destuructor不称为班级成员和基类攻击方的灾难
- 按行读取文本文件,使矢量为空
- 可以使未命名的结构静态
- 是否可以使整数仅收到一个单个数字而不是两个接收输入
- LD_BIND_NOW可以使可执行文件运行得更慢?
- 是否可以使头文件使文本居中?- 在控制台中
- 是否可以使您的Qt应用程序在运行时不锁定文件
- visualstudio-是否可以使vs2008c++项目从另一个文件导入源文件名