Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ warning: pragma once in main file

Tags:

c++

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

like image 895
Jakub Zilinek Avatar asked May 15 '20 20:05

Jakub Zilinek


People also ask

Where do you put pragma once?

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.

What does pragma once mean in C?

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.

Should all header files have pragma once?

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.

Is #pragma once standard?

#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.


1 Answers

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.

like image 78
eerorika Avatar answered Oct 17 '22 13:10

eerorika