-
如何在C++代码里include一个标准C头文件
#include 一个标准头文件(比如<cstdio>),你通常不必作任何事。比如:
// 这是C++代码 #include <cstdio> // #inlcude行没有什么不寻常的 int main() { std::printf("Hello world\n"); // 调用也没什么不寻常的 ... }
如果你认为std::printf()调用中std::部分不寻常,那么你最好“克服它(get over it)”。这句话的意思是使用标准库中名字的标准方式,因此,你现在就应该习惯它。
然而,如果你正在使用C++编译器编译C代码,你可能不想把所有的printf()的调用转换成std::printf()。幸运的是,这种情况下C代码可以使用旧风格的头文件<stdio.h>而不是新风格头文件<cstdio>和namespace的怪诞。
/* 这是C代码,这里用C++编译器编译 */ #include <stdio.h> /* #inlcude行没有什么不寻常的 */ int main() { printf("Hello world\n"); /* 调用也没什么不寻常的 */ ... }
-
在我的C++代码中如何include一个非系统的C头文件
如果你要包含的C头文件不是由系统提供的,你可以把#include包裹在extern “C” { /* here */ }结构里。这就告诉C++编译器在头文件中声明的函数是C函数。
// 这是C++代码 extern "C" { #include "my-C-code.h" // 获得声明f(int i, char c, float x) } int main() { f(7, 'x', 3.14); // 注意:调用没什么特别的 ... }