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?

4
  • 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. Commented Oct 22, 2012 at 23:22
  • 3
    @Praetorian: But maybe not a .png file. Commented Oct 22, 2012 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. Commented Oct 22, 2012 at 23:33
  • @chris Watch the gif from the second answer in James' link Commented Oct 22, 2012 at 23:37

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.