简体   繁体   English

C++ 警告:pragma once 在主文件中

[英]C++ warning: pragma once in main file

I'm have an issue with compiling my program with g++ 8.3.我在使用 g++ 8.3 编译程序时遇到问题。 I have approx 10 classes in a program.我在一个程序中有大约 10 节课。 These classes are placed in header files and their full definitions are in .cpp files.这些类放在 header 文件中,它们的完整定义在.cpp文件中。 I'm including these classes the same way as in this code:我以与此代码相同的方式包含这些类:

main.cpp:主.cpp:

#include "CPerson.h"

int main()
{
    CPerson person1(10 , "Peter");
    CPerson person2(20 , "James");
    person1.Print();
    person2.Print();
    return 0;
}

CPerson.h: 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:当我尝试使用以下命令编译这个 C++ 程序时:

g++ main.cpp CPerson.h g++ main.cpp CPerson.h

I get this message:我收到这条消息:

warning: #pragma once in main file警告:#pragma once 在主文件中

Is here anything I can do about this, or is it just bug in the g++ compiler?我对此有什么办法吗,或者它只是 g++ 编译器中的错误?

SOLVED:解决了:

You need to compile only.cpp files with declarations of methods of each class thats defined in Class.h您需要编译 only.cpp 文件,其中包含 Class.h 中定义的每个 class 的方法声明

You get the warning because you are compiling a file that contains #pragma once .您收到警告是因为您正在编译一个包含#pragma once的文件。 #pragma once is only intended to be used in headers, and there is no need to compile headers; #pragma once只打算在headers中使用,不需要编译headers; hence the warning.因此警告。 Solution: Don't compile headers.解决方案:不要编译标头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM