which #include method is better....

Started by
12 comments, last by ToohrVyk 18 years, 8 months ago
Quote:Original post by ToohrVyk
Quote:Original post by DigitalDelusion
Oh, and about speed, modern compilers are smart enough to not reread headers included multiple times rendering use of "hacks" like #pragma once needless to.


Is this really a good thing? Consider the following situation:

<following situation>

A "smart" compiler that ignores duplicate includes will display "1", a standards-respecting compiler would display "2.00000".

I think I read somewhere that some compilers* actually store some form of parse tree from the header, so they can correctly handle multiple includes of the same file with different #defined tokens but still avoid re-parsing the file each time. So the difference in speed between #pragma once and inclusion guards could typically be measured in clock ticks, whereas the difference between re-reading the file for the above situation and re-processing the parse tree is much more significant.

Enigma

*I think this was an article refering to gcc. Of course that could be obsolete information, bad information or plans for a future implementation, I don't recall the article well enough to be sure.
Advertisement
Quote:Original post by Ready4Dis
A "smart" compiler should complain of multiple function declarations, so a standards compiler would not display 2, it wouldn't display anything but an error ;).


In C++, declaring int foo(int bar) and float foo(float bar) is allowed (and known as function overloading). The difference in behavior relied on the fact that I was passing the function a float (with an int, both compilers would have behaved the same way), hence triggering the use of different overloads of the function if they are available.

And since the (devilish, I agree) include guards prevent the definition of each function more than once, the compiler has nothing to complain about.

You are right, however, that it would be wise to add the keyword "static" to the functions, so the linker won't throw a fit when it notices the functions being defined in several compilation units. If we were crazy enough to use this code in a project with more than one cpp file. [grin]
Quote:Original post by ToohrVyk
You are right, however, that it would be wise to add the keyword "static" to the functions, so the linker won't throw a fit when it notices the functions being defined in several compilation units. If we were crazy enough to use this code in a project with more than one cpp file. [grin]

It would be smarter to add them to the anonymous namespace, since the use of static in this situation is deprecated (link).

Enigma
I have obviously been using C too much lately. *hangs himself*

This topic is closed to new replies.

Advertisement