Tag: guard

Should you use #pragma once?

Should you use #pragma once?

Pragma as found by google image searchThe traditional way of using an include guard is to put all of the header inside a #ifdef like this.

#ifndef hr_time
  #define hr_time
  #include <linux/time.h>
  #include 

// rest of code here
#endif

However the modern way is to put this at the top of the header file.

#pragma once

And this seems supported by most compilers I’ve tried. Certainly Visual Studio C/C++, gcc and clang all work.

In fact when you add a new file and choose header in Visual Studio, it put the #pragma once in automatically for you!

Given that those three C compilers are the main ones I use, I much prefer this pragma and use it.  But I would be interested in hearing of any C compilers that don’t  use it.

 

That Clang C compilation

That Clang C compilation

I spent about five hours trying to get the timing code to compile before I got it compiling and working. Now I’m used to the concept of include guards in C. Those are the #ifndef that you see like this:

#ifndef _timeh
  #include <linux/time.h>
  #define _timeh 1
#endif

But in the hr_time.c file these include guards are on steroids. Not only did I need to include <time.h>, I also had to include <linux/time.h> but with a couple of extra #defines in there. It doesn’t seem right and wasn’t needed with the Windows version.  I’d welcome any comments on this.

#ifndef _timeh
  #include <linux/time.h>
  #define __timespec_defined 1 
  #define __itimerspec_defined 1
  #include <time.h>
  #define _timeh 1
#endif

The sdldemo program with timing whown in the window caption.Without these, I’d get compile errors like __timespec redefined errors.

I’ve uploaded the source files and Visual Studio Code JSON files for this in the file asteroids_ch25.zip in the new repository for the Learn C on Linux Ebook

So feel free to try it. The only difference between this and the version shown in an earlier post is the time (in the window caption) to draw all 100,000 rectangles,  You’ll need to install SDL2 if you want to compile and run the program.