2

I've seen std::string used in a .c file. std is a c++ namespace and namespaces were introduced in c++. Why is that so? Shouldn't it throw an error?

Shoe
  • 74,840
  • 36
  • 166
  • 272
  • This is your answer. Flagged as duplicate. http://stackoverflow.com/questions/1545080/correct-c-code-file-extension-cc-vs-cpp – ApplePie Oct 22 '12 at 23:22
  • 1
    File extensions don't matter, I can write code in a *.mp3 file, and my compiler will happily compile it as C++ if I ask it to. – Praetorian Oct 22 '12 at 23:22
  • 3
    @Praetorian: [But maybe not a .png file.](http://stackoverflow.com/questions/5508110/why-is-this-program-erroneously-rejected-by-three-c-compilers) – James McNellis Oct 22 '12 at 23:28
  • @JamesMcNellis, I think there's a video somewhere of someone imaging a BMP or something and changing the extension to a working C++ program. – chris Oct 22 '12 at 23:33
  • @chris Watch the gif from the second answer in James' link – Praetorian Oct 22 '12 at 23:37
  • @Praetorian, Wow, it was *right* there! – chris Oct 22 '12 at 23:45

2 Answers2

9

Yes, it will cause numerous compiler errors if it's compiled as C code. If it's being compiled as C++ instead, then it will compile fine. For example, GCC has the -x option to select the language to compile as, so you can compile a .c as C++ if you want with -x c++. Likewise, the Microsoft Visual C++ compiler has the options /Tc and /Tp to select a source language of C and C++ respectively.

I suggest you fix your build system so that it doesn't pass the -x c++ or /Tp flag to files not ending with typical C++ source file extensions (.cc, .cpp, .cxx, c++, and .C, though the last three are quite rare).

Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
1

The extension of a file is only there to help you as the reader. The compiler does not care as long as you use a c++ compiler.

learnvst
  • 15,455
  • 16
  • 74
  • 121