Why do I have to name my text file <something>.cpp in order to compile a C++ program from command line?
I'm exploring compiling/running simple C++ programs from the bash shell (in Ubuntu 12.04). Being new to Linux in general, I actually have a couple questions.
First, it seems that Ubuntu/Linux does not display file types in the .abc format, as Windows does. I get that the OS doesn't need that extension to know the file's type, but isn't it more convenient for the human user to be able to read off that information at a glance? How am I supposed to know what type a given file is?
Second (and relatedly), if Linux seems not to care about extending a file name with the type information, why is that when I create a simple C++ program in gedit and just call it 'test', the compilation doesn't work (using the g++ compiler btw), but when I name the file 'test.cpp', it does work?
Does Linux need/care about the extension, or not? I feel like I'm getting mixed messages here, and I would really like to understand.
Solution 1:
You don't have to name your file with a particular suffix, however the gcc/g++ compilers use the suffix as a shortcut to decide how to process the files. If you want to use a different suffix (or no suffix) you can tell the compiler what kind of file it is explicitly using the -x
command line option - see the answer to this similar previous question Compiling C source file without .c suffic
Solution 2:
In any operating system, what you said is correct: a file's extension does not determine the type of file. Extensions are used to tell programs (and humans) what to expect the file's type to be. Generally, files with no extension are binaries, however, that is not a strict rule.
Does it matter if a file has an extension? It depends on the program. Some, like OpenOffice or Gedit, will not ask any questions about the file name extension, but will open the file anyway regardless of what error may occur. Smarter programs like g++ will examine the file name extension before parsing to prevent human error. And then there are programs like media players that trust you to use the correct extension for a file and use the extension to determine how to run.
In conclusion you could say that Linux doesn't care very much about file name extensions. This leaves it up to humans and programs to make educated decisions about naming their files. Extensions have their place, but they are not the determinant on what a file is.