+ 5
#pragma once vs #ifndef
So turns out these both do the same thing. Is it okay to use both? Which do you use?
9 odpowiedzi
+ 5
Apparently, it seems that #pragma once is faster and more versatile than the include guards we normally use in headers.
#pragma once can be written anywhere in the program and it is assumed to be less prone to bugs, that is why it is more preffered than the error-prone include guards...
But the true nature of pragma can get as complicated as why we shouldn't use using namespace std;
Also #pragma is compiler dependent, and so the header may not work cross-platform...
The main disadvantage of pragma is that it that is assumes that if the file paths of two headers are different, while their content is the same, the headers are different...
If you copy a same header in a different folder and include them both in your program, pragma once will suppress only one header, not the other, even when it should have...
Eg -
head.h
#pragma once
#include<iostream>
#define print(x) std::cout<<x;
//Now we copy it to h1\\ folder.
main.cpp
#include"head.h" //Included...
#include"head.h" //Not included...
#include"h1/head.h" //Included?...
+ 5
lol. much of a muchness really!. I will just keep using both for now as you suggest. When I goto compile this code on my Ubuntu box I will worry about it then 😊 Thanks again Kinshuk!
+ 4
So in other words, ifndef is better?
*if you plan to deploy cross platform
*if you have a large project with multiple people working on it
I have been using both, should I stop doing this?
i.e
#ifndef HEADER_H
#define HEADER_H
#pragma once
// code
#endif //HEADER_H
edit: you answered this before I even typed it 😆
+ 4
good. When you say faster, do you mean compile time right? Using ifndef will not affect execution time, correct?
+ 3
In all the star cases you gave above, ifndef proves to be a safer option...
But using both is the best...
+ 2
So, many people use pragma only when they trust their compiler and keep their headers in a single folder...
Also, some people prefer to use both together, as this helps keep the advantages of both...
Eg:
#pragma once
#ifndef HEAD_H
#define HEAD_H
//Code here
#endif //HEAD_H
+ 2
@jay
Ifndef is not better, but slower than pragma once.
But it is safer in many aspects and error prone in others.
So, it is best to use both, like you're doing in the code above...
+ 2
Yes. And in GCC and Clang, the difference in the compilation time taken by ifndef and pragma once is just some milliseconds (maybe 10 - 15)...
That much time shouldn't slow your code down...
+ 2
@jay
Welcome ^_^