Why do all the C files written by my lecturer start with a single # on the first line?

时光总嘲笑我的痴心妄想 提交于 2019-12-29 10:03:32

问题


I'm going through some C course notes, and every C program source file begins with a single # on the first line of the program.

Then there are blank lines, and following that other stuff followed by the main function.

What is the reason for the #?

(It's out of term now and I can't really ask the chap.)

Here's an example:

#

#include <stdio.h>
int main() {
   printf("Hello, World!");
   return 0;
}

回答1:


Wow, this requirement goes way back to the 1970s.

In the very early days of pre-standardised C, if you wanted to invoke the preprocessor, then you had to write a # as the first thing in the first line of a source file. Writing only a # at the top of the file affords flexibility in the placement of the other preprocessor directives.

From an original C draft by the great Dennis Ritchie himself:

12. Compiler control lines

[...] In order to cause [the] preprocessor to be invoked, it is necessary that the very first line of the program begin with #. Since null lines are ignored by the preprocessor, this line need contain no other information.

That document makes for great reading (and allowed me to jump on this question like a mad cat).

I suspect it's the lecturer simply being sentimental - it hasn't been required certainly since ANSI C.




回答2:


Does Nothing

As of the ISO standard of C/C++:

A preprocessing directive of the form

# new-line

has no effect.

So in today's compilers, that empty hash does not do anything (like- new-line ; has no functionality).


PS: In pre-standardised C, # new-line had an important role, it was used to invoke the C Pre-Processor (as pointed out by @Bathsheba). So, the code here was either written within that time period, or came from habit.




回答3:


You need to know about the Compilation process of C. Because that is "must know" how the Source code converting into Executable binary code (file).

From the Compilation Process, the C source code has to Cross the pre-processor Section. But how to tell the Compiler to pre-process the code?... That the time # Symbol was introduced to the indicator of Preprocess to the compiler.

For Example #define PI 3.141 is in the Source code. Then it will be change after the Preprocessing session. Means, all the PI will be changed into 3.141.

This like #include <stdio.h>, the standard I/O Functions will be added into your Source code.

If you have a Linux machine, compile like gcc -save-temps source_code.c. And see the compiler outputs.



来源:https://stackoverflow.com/questions/45629176/why-do-all-the-c-files-written-by-my-lecturer-start-with-a-single-on-the-first

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!