Why isn't C/C++'s “#pragma once” an ISO standard?

前端 未结 9 1690
说谎
说谎 2020-11-28 11:29

I am currently working on a big project and maintaining all those include guards makes me crazy! Writing it by hand is frustrating waste of time. Although many editors can g

9条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 12:21

    Include guards are definitely an annoyance, and C should have originally been designed such that headers would be included once by default - requiring some special option to include a header multiple times.

    However, it wasn't ,and you're mostly stuck with having to use include guards. That said, #pragma once is pretty widely supported so you might be able to get away with using it.

    Personally, I solve your 1st problem (similarly named include files) by adding a GUID to the include guard. It's ugly, and most people hate it (so I'm often forced to not use it at work), but your experience shows that the idea has some value - even if it is hideously ugly (but then again the whole include guard thing is kind of a hack - why not go whole hog?):

    #ifndef C_ASSERT_H_3803b949_b422_4377_8713_ce606f29d546
    #define C_ASSERT_H_3803b949_b422_4377_8713_ce606f29d546
    
    // blah blah blah...
    
    #endif
    

    I've heard that compilers don't actually reopen header files that have include guards (they've learned to recognize the idiom). I'm not sure if that's true (or to what extent it's true); I've never measured it. I also don't worry about it, but my projects aren't so huge that it's a problem.

    My GUID hack pretty much solves items 1, 5, and 6. I just live with items 2, 3, and 4. Actually, for item 2 you could live without renaming the include guard macro when you rename the file as the GUID will ensure it remains unique. In fact, there's no reason to incorporate the filename at all with the GUID. But I do - tradition, I suppose.

提交回复
热议问题