C 标准库中的函数可以在 C++ 中使用吗?

Can functions from the C standard library be used in C++?

现在我正在熟悉 C 和 C 标准库,我想知道我在这方面的知识是否对我以后转向使用 C++ 有用。

因此我想知道,我是否可以在 C++ 设置中使用 C 标准库提供的函数,以及实际这样做是否有意义以及为什么这样做。

是的,C++ 最初的设计目的是让任何 C 库都可以在 C++ 中轻松使用。当然这不太正确(特别是,如果 C 库碰巧使用某些 C++ 关键字,如 trydynamic_cast,它不会工作;另外,如果 callback 编码在传递给 C 库的 C++ 中引发了一些异常,你可能会遇到大麻烦)。

在 C++ 中使用 C 头文件的标准做法是

 extern "C" {
 #include <some_c_header_file.h>
 };

和大多数 现有的 C 头文件旨在通过实际包含诸如

之类的内容来与 C++ 协作
 #ifdef __cplusplus
 extern "C" {
 #endif

 //// most of the header material goes here, C style

 #ifdef __cplusplus
 }; // end extern "C"
 #endif

在实践中,许多 C 标准头文件都有等效的 C++ 头文件来包装上面的东西(也在 namespace std 中)。例如 C <stdio.h> 是 C++ <cstdio> - 但您通常应该更喜欢真正的 C++ 流 (<iostream>),但是 printf-like 例程通常更 localization friendly mixed with gettext(3).

但是 C 和 C++ 是非常不同的语言。 您应该使用惯用的 C++11 进行编码(使用标准 C++ containers, auto, closures, RAII, smart pointers, rule of five, SFINAE, exceptions, anonymous functions,...)

一些标准的 C 函数在惯用的 C++ 中不是很有用。例如,您不太可能在 genuine C++ 中直接使用 malloc(至少更喜欢 new - 这仍然是级别非常低,不再符合 C++ 精神 - 更有可能使用大量容器和智能指针 而无需 手动处理堆分配)。但是POSIX functions (notably syscalls(2) ....) are quite useful in C++. longjmp很可能与C++异常不兼容。

顺便说一句,C++ 在本世纪 发展了很多 。不要学习 C++98,但至少 C++11 (there are tremendous differences between them) and perhaps C++14. Use a recent compiler (GCC or Clang/LLVM); in december 2015, that means GCC 5 at least or Clang/LLVM 3.7。不要忘记在编译器中启用所有警告和调试信息(例如 g++ -Wall -Wextra -g -std=c++11

C++(至少意味着 C++11)是一种困难的编程语言,比 C 复杂得多。您需要阅读数周才能了解其中的一些内容,良好的编码风格和纪律是必不可少的(您可以轻松地用 C++ 编写非常糟糕的代码)。从 Programming: Principles & Practice Using C++

开始

我相信,如果你只懂 C,在学习 C++ 之前阅读 SICP(并学习一点 Scheme)是值得的。

这个概念undefined behavior is very important, both in C and probably even more in C++. You absolutely need to understand it (see C.Lattner's blog on it) and avoid吧。

通过研究(并可能参与)一些现有的 free software 及其源代码,您还将学到很多东西。因此我建议使用 Linux.

我只引用 ISO/IEC N3690(c++ 标准)中的一段。

17.2 The C standard library

1 The C++ standard library also makes available the facilities of the C standard library, suitably adjusted to ensure static type safety.

所以很简单!

是的。您可以在 C++ 中使用标准的 C 库函数 例子

    stdio.h   => cstdio   (printf/scanf)
    math.h    => cmath     (sqrt)