Is it bad practice to use a C header instead of its C++ equivalent in C++ (e.g. stdio.h instead of cstdio)?

前端 未结 4 1131
北海茫月
北海茫月 2021-01-14 04:22

It seems that a lot of people include example.h instead of cexample in their C++ code. I know that everything in the C++ versions is declared in namespace std, but I\'m not

相关标签:
4条回答
  • 2021-01-14 04:53

    The difference between the two is that the C headers that C++ imported (by prefixing with c and removing the .h suffix) are in namespace std. This so any call or use of a standard facility is prefixed with std::, for uniformity. It's The Standard Way Of Doing Things(tm). Unless of course you already have a bunch of C code in which you don't feel like appending std:: to each standard call: then use the classic C headers.

    0 讨论(0)
  • 2021-01-14 04:54

    For example stdio.h is not the same as cstdio. The latter includes the first, but then undefines some macros and replaces them with real functions. Personally I would always go with the C++ headers!

    0 讨论(0)
  • 2021-01-14 05:08

    It's OK. But it somehow seems neater to to use the C++ style (i.e. no .h extension) in C++ code. I wouldn't (and I don't) worry about it.

    0 讨论(0)
  • 2021-01-14 05:11

    when working with C++, I prefer to use C++ header syntax unless there's a reason not to. It also appears to be safer to use the <name> (with no .h syntax) based on the following comments in the standard:

    Section 17.4.1.2, paragraphs 3 and 4 (ISO/IEC 14882, Second edition 2003-10-15) state:

    The facilities of the Standard C Library are provided in 18 additional headers, as shown in Table 12:

    It then lists off the table, e.g. <cassert>, <ciso646>, ... and then continues

    Except as noted in clauses 18 through 27, the contents of each header cname shall be the same as that of the corresponding header name.h....

    Thus, the standard defines the headers without the .h but does indicate that, for the most part, they are identical to those provided by the C compiler and provides clauses 18-27 to identify the differences.

    Unfortunately, I can't figure out where those sections are in the standard to be able to document the differences should they be useful.

    I don't believe there is a requirement that the .h headers be present when using a C++ compiler.

    As @James pointed out in a comment, Section D.5, paragraphs 1 and 2 state that the C headers must be present:

    ... the C++ Standard library provides the 18 C headers....

    Every C header, each of which has a name of the form name.h behaves as if each name placed in the Standard library namespace by the corresponding cname header is also placed within the namespace scope of the namespace std and is followed by an explicit using-declaration (7.3.3)

    0 讨论(0)
提交回复
热议问题