I'm have an issue with compiling my program with g++ 8.3. I have approx 10 classes in a program. These classes are placed in header files and their full definitions are in .cpp
files. I'm including these classes the same way as in this code:
main.cpp:
#include "CPerson.h"
int main()
{
CPerson person1(10 , "Peter");
CPerson person2(20 , "James");
person1.Print();
person2.Print();
return 0;
}
CPerson.h:
#pragma once
#include <iostream>
#include <string>
using namespace std;
class CPerson{
protected:
int m_Age;
string m_Name;
public:
CPerson( const int age , const char * name ) :
m_Age(age), m_Name(name){}
void Print(){
cout << "Hello Im " << m_Name << " - " << m_Age << "years old" << endl;
}
};
When I try to compile this C++ program with the following command:
g++ main.cpp CPerson.h
I get this message:
warning: #pragma once in main file
Is here anything I can do about this, or is it just bug in the g++ compiler?
SOLVED:
You need to compile only .cpp files with declarations of methods of each class thats defined in Class.h
Using #pragma once will delegate the task, of detecting subsequent #include statements for the same file, to the compiler. It can do this efficiently and safely. As a user, there is no room for mistakes. Just place the directive in the first line of every header file.
In the C and C++ programming languages, #pragma once is a non-standard but widely supported preprocessor directive designed to cause the current source file to be included only once in a single compilation.
Be careful not to use #pragma once or the include guard idiom in header files designed to be included multiple times, that use preprocessor symbols to control their effects. For an example of this design, see the <assert. h> header file.
#pragma once is a non-standard pragma that is supported by the vast majority of modern compilers. If it appears in a header file, it indicates that it is only to be parsed once, even if it is (directly or indirectly) included multiple times in the same source file.
You get the warning because you are compiling a file that contains #pragma once
. #pragma once
is only intended to be used in headers, and there is no need to compile headers; hence the warning. Solution: Don't compile headers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With