Remove #pragma once warnings - c++

I am using #pragma once in my .cpps and .hpps and because of that I get a warning for each file that uses it. I have not found any option to disable this kind of warning, only the thing of #ifndef MY_FILE_H #define MY_FILE_H /*...*/ #endif.
So would you recommend me to replace each #pragma once with ifndefs?
in header:
#define MYFILE_H
// all the header
and in the other files:
#ifndef MYFILE_H
#include "myfile.hpp"
#endif
// the rest of the file
What do you think, is it better to use it like this? Or there is an option to disable the #pragma once warnings in GCC, that I do not know?

The common approach is to place the guard in the .h file only:
#ifndef MYFILE_H
#define MYFILE_H
// all your myfile.hpp here
#endif
or
#pragma once
// all your myfile.hpp here
The rest of files (other .cpp) should do nothing regarding the guards. You should not get warnings by doing this.

Indeed the #ifndef guard can always be used, but just to remove the warning while compiling the source which uses #pragma once I would recommend to use the -woption while compiling.
e.g. gcc -w -o <output file> <input file(s)>

Related

Include precompiled header in ifdef

I have a cross-platform project and thing is on Windows I want to use precompiled headers(its really vital in this case) and Linux I dont want it. So I would like to have something like this:
#ifdef _WIN32
#include "precompiled.h"
#endif //#ifdef WIN32
When I build on Windows I get this annoying error, claiming:
PCH warning: header stop cannot be in a macro or #if block. An intellisense pch was not generated
Is there any workaround to fix this issue?
Thanks on advance.
I already have this problem and for me one of these two options worked for me.
1) Maybe if you add #pragma once at the start of the file (even before the #ifndef _WIN32 header guard).
2) Or you can add on your header files this skecth:
#ifndef MYHEADER_H
#define MYHEADER_H
... contents of myheader.h
#endif /* MYHEADER_H */
This will guarantee your header will be compiled just once and this warning will disapear (at least for me).
Hope it works!

Get current compilation unit name within #include

My current goal is to create one (or as few as possible) line of code that will switch the remainder of the active compilation unit to an unoptimized, debug configuration. My first instincts were either:
FORCE_DEBUG;
// code below here will be forced to be unoptimized and in a debug environment
or
#include "ForceDebug.h"
// code below here will be forced to be unoptimized and in a debug environment
would be ideal. In my workspace, to convert to an unoptimized debug configuration requires I change the pragma optimize level, but also #undef some macros and #define other macros.
The FORCE_DEBUG macro doesn't work because it would need to execute preprocessor directives #undef and #define which I understand are not evaluatable within a macro.
Instead I have a working version of #include "ForceDebug.h". But I want to message the developer that they have disabled optimization on a given compilation unit (so they don't check it in, or if they do check it in that it can be caught and fixed). Ideally this message includes the filename of whichever file #includes "ForceDebug.h" or the current compilation unit.
Here's an approx ForceDebug.h
#pragma once
#pragma message("DISABLING OPTIMIZATION IN" COMPILATION_UNIT_FILE)
#undef _RELEASE
#define _DEBUG
#ifdef _MSC_VER
# pragma optimize("", off)
#else
# pragma GCC optimize("O0")
#endif
So a call site would look something like Foo.cpp:
// this messages "ForceDebug.h", I want to message "Foo.cpp"
//#define COMPILATION_UNIT_FILE __FILE__
// double macro also messages "ForceDebug.h"
//#define COMPILATION_UNIT_FILE COMPILATION_UNIT_FILE2(__FILE__)
//#define COMPILATION_UNIT_FILE2(x) x
// this works but requires doing it manually, which I'm trying to avoid
#define COMPILATION_UNIT_FILE "Foo.cpp"
#include "ForceDebug.h"
// code below here will be forced to be unoptimized, debug environment
I can't use __FILE__ because that messages about ForceDebug.h, when I want it to report about Foo.cpp.
If I could evaluate __FILE__ inside Foo.cpp and pass the evaluated version into ForceDebug.h that would be acceptable, but I tried recursive macro calls and it still reported ForceDebug.h
Is there any way to get it to pass "Foo.cpp" into the include or to derive that value by some other means for either clang or Visual Studio?
I was not able to find a way to emit the current compilation unit name from an included file.
However, your proposed syntax requires the user of "ForceDebug.h" to add another directive to expose its compilation unit name to the header file. Instead, you can turn it around and allow simple inclusion that defines a macro that allows for the message to be emitted.
While, generally speaking, macros cannot be used to generate pre-processor directives, there is a syntax for pragmas for the compilers you illustrated. MSVC and GCC each have their own syntax, but conditional compilation can make the syntax appear uniform.
In your source file:
#include "ForceDebug.h"
FORCE_DEBUG;
//... rest of source
In "ForceDebug.h":
#pragma once
#ifdef _MSC_VER
#define DO_PRAGMA(X) __pragma(X)
#define NO_OPT optimize("", off)
#else
#define DO_PRAGMA2(X) _Pragma(#X)
#define DO_PRAGMA(X) DO_PRAGMA2(X)
#define NO_OPT GCC optimize("O0")
#endif
#define FORCE_DEBUG \
DO_PRAGMA(message("DISABLING OPTIMIZATION IN " __FILE__)) \
DO_PRAGMA(NO_OPT) \
struct __force_debug
#undef _RELEASE
#define _DEBUG
You could use the __FILE__ predefined macro like below:
#pragma message("DISABLING OPTIMIZATION IN " __FILE__)
Live Demo
Edit:
Since you want to report about the .cpp file I would go the other way around. That is, I would change ForceDebug.h to:
#pragma once
#undef _RELEASE
#define _DEBUG
#define OPT_OFF
^^^^^^^^^^^^^^^
#ifdef _MSC_VER
# pragma optimize("", off)
#else
# pragma GCC optimize("O0")
#endif
And then I would put the potensial message in my .cpp file:
#include "foo.h"
...
#ifdef OPT_OFF
#pragma message("DISABLING OPTIMIZATION IN " __FILE__)
#endif

How can I use the #error directive to provide the user pointers to useful information?

Suppose I have a file like the following
Mainfile.cpp
#include "stdafx.h"
#include <stdlib.h>
#include "Myfile.h"
#ifdef _MYFILE
#error Myfile.h to be included. Please refer Ream Me at C:\ReadMe
#endif
int _tmain(int argc, _TCHAR* argv[])
{
system("pause");
return 0;
}
Myfile.h
#pragma once
#undef _MYFILE
#define MYFILE
My goal is to provide additional information ("Please refer to ....") in case something is missing (MyFile.h was not included/found on the path).
How can I handle this with a third party library, like Boost? In this case, I don't have control on Boost and I cannot handle the definition of _MYFILE: then how can throw the error?
Pseudo code
#include "boost/boost.h"
#if (boost is not included || directory path is not set || boost .h file not found)
#error: Set boost path and compile again
#endif
It is impossible to do what you want in C/C++ code. Once you enter #include "myfile.h" it is up to compiler to locate that file and throw an error if it's nowhere to be found.
You are also misusing #ifndef ... #error ... #endif.
Some people use it to track header dependencies; imagine you have a header messages.h which requires header mytypes.h. Usually you just write something like this:
// File mytypes.h
#ifndef MYTYPES_H
#define MYTYPES_H
typedef unsigned char UINT8;
// ...
#endif
// File messages.h
#ifndef MESSAGES_H
#define MESSAGES_H
#include "mytypes.h"
// ...
#endif
But you can also write messages.h like that:
#ifndef MESSAGES_H
#define MESSAGES_H
#ifndef MYTYPES_H
#error I need mytypes.h to compile!
#endif
#endif
but it quickly becomes a chore to insert #errors for all the headers you depend on and then include those dependencies over and over again in all the source files where your header is needed. So in most cases first approach is the way to go.
You also need to decide what type of include guard you want to use. Don't #define MYFILE if you're already using #pragma once. Choose one and stick to it. (and remember that #pragma once is nonstandard).
Finally last but not least: if you really need to be that user friendly you will need to use your build system to verify that all extra libraries are installed and their headers are available. My guess is you're using Visual Studio's native builder. I don't know that one but I read it has pre-build actions so perhaps it's possible to define one which verifies boost location via some native visual studio calls or simply by running a batch file included in the project.
Shouldn't
#if _MYFILE
#error Myfile.h to be included. Please refer Ream Me at C:\ReadMe
#endif
be
#ifndef _MYFILE
#error Myfile.h to be included. Please refer Ream Me at C:\ReadMe
#endif

What is the reason for #pragma once inside header guards?

Just seen this inside <boost/asio.hpp>
#ifndef BOOST_ASIO_HPP
#define BOOST_ASIO_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
/// ....
#endif // BOOST_ASIO_HPP
Disregarding the _MSC_VER preprocessor checks, what is the benefit of having the #pragma once in this case? Doesn't the preprocessor header guard ensure in all cases and on all platforms, the header contents are only ever included once?
#pragma once specifies that the file will be included (opened) only once by the compiler when compiling a source code file. This can reduce build times as the compiler will not open and read the file after the first #include of the module.
If you don't #pragma once, the file will be opened each time it is needed and compiler will stop parsing it on #ifndef BOOST_ASIO_HPP, if it has been defined.
Specifies that the file will be included (opened) only once by the compiler in a build. This can reduce build times as the compiler will not open and read the file after the first #include of the module
And one more related question from SO
Yes header guards ensures that the header contents are included only once. but here you are using #pragma for checking another definition and not include file.
The below link is existing question on header guards in SO.
Purpose of Header guards
#pragma once has the same purpose, but include guards are intended to require a deeper analysis to ensure a file is included exactly once - e.g.
// somerandomfileinmyproject.cpp
#undef BOOST_ASIO_HPP
#include <bost/asio.cpp>
Unless the compiler does handle such cases correctly, it still needs to open the file and pass it through the preprocessor even though it has been included before.
You can reproduce the effect of the #pragma once in a standard way using the following:
#if !defined GUARD_SYMBOL
#include "GUARDED_FILE"
#endif
although it is much more verbose. As others have said, it helps with compilation times since the file is not searched for / opened instead of opening the file and ignoring everything inside it - the file still has to be parsed by the preprocessor.

redefinition c++

how does header including in c++ work? I have the classes already implemented in .h file and when there is #include in two files, there's this error:
files.h:14:7: error: redefinition of ‘class abstract_file’
files.h:14:20: error: previous definition of ‘class abstract_file’`
multiple times for each class and enum.
Can anyone explain this?
Using include in C++ simply takes the file included and splats the contents into where it is included. To do this without worrying about multiple includes of the same file, you want to use header guards. Use this basic format for all header files:
#ifndef FILENAME_H
#define FILENAME_H
class foo (or whatever else is in the file!) {
...
};
#endif
You can only include a definition one time but headers can be included multiple times. To fix that, add:
#pragma once
to the top of each header file.
While #pragma once is relatively common, if you are using an older compiler it may not be supported. In that case, you need to fall back on manual include guards:
#ifndef MY_HEADER_H
#define MY_HEADER_H
...
#endif
(note that you need to replace MY_HEADER_H with a unique string for each header file)
header files usually define a unique symbol so that they are only included once.
e.g.
#ifndef _myheader_h
#define _myheader_h
// rest of header goes here
#endif
Some compilers support
#pragma once
See Pragma Once on wikipedia.
While many people have solved your error for you, it seems that nobody has answered your initial question:
how does header including in c++ work?
When the preprocessor finds an #include directive it replaces it by the entire content of the specified file.
You can read more on preprocessor directives at cplusplus.com.
Update: To illustrate this, you could try the following if you have gcc handy:
echo '#include <iostream>' > test.cxx
gcc -E test.cxx
You'll see the contrents of iostream whizz past your eyes as the preprocessed source code is sent to standard output.
What you can do is to guard your header from multiple inclusions:
#ifndef MY_HEADER__
#define MY_HEADER__
/* your stuff goes here! */
#endif
You can also use:
#pragma once
but it is not standard although it is supported by many compilers.
Use include guards in header files:
#ifndef FILES_H
#define FILES_H
struct foo {
int member;
};
#endif // FILES_H
This makes sure that your header will only get included once.
Another method is to use #pragma once in your header files, but it's not standard C. It's supported by Visual C, GCC and Clang though, so most likely it's ok to use.