开发者

the extension of a source file

开发者 https://www.devze.com 2023-03-28 05:59 出处:网络
A compiler checks the syntax of source code from the text file. Why is it necessary to save it with an extension .c or .cpp开发者_JAVA百科?

A compiler checks the syntax of source code from the text file. Why is it necessary to save it with an extension .c or .cpp开发者_JAVA百科?

I tried this on gcc but it does not compile a file with an extension other than .c and .cpp!!


GCC (you name it on your tags) checks the file extension, if you do not specify a language with the -x option.

If the extension is not recognized, the file is passed directly to the linker.


The compiler won't guess the language of the code in a file by looking at the text - you have to tell it what to compile as. Nearly every compiler allows this to be passed as a flag or it will infer it from the file extension. You're quite free to compile a .cpp file as pure C by passing the appropriate flag to your compiler so it needn't infer it. However, this is a situation where following convention helps both you (less flags to pass around) and other programmers (who know the language from a quick ls).


It's not necessary -- just convenient. You can use any extension you want, but using the standard extensions makes it easy for compilers, the operating system, and other programmers to know what the file contains.


The compiler typically uses the extension to decide what language you intended the file to contain, so if it's .c, it'll treat the file as containing C source code. If it's .C (note, upper-case), .cc, .cpp, etc., it'll treat it as C++. Depending on the compiler, it might also recognize other extensions (e.g., .pas, .f, .cs, etc.)


Usually, .c files contain C and .cpp files contain C++.

Compilers often use the extension to determine which language it can find in a source file. Even files that contain pure C, but are saved with a .cpp extension, will usually be interpreted as C++. Although for the most part, C++ is a superset of C, there are subtle differences between these languages, so the code might be treated differently.

You can tell most compilers to treat any file as a certain language. How this is done differs from compiler to compiler, e.g GCC uses the -x option.

FWIW, I think GCC also accepts .cc as C++. But that may have been a thing of the past.

0

精彩评论

暂无评论...
验证码 换一张
取 消