繁体   English   中英

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

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

我在使用 g++ 8.3 编译程序时遇到问题。 我在一个程序中有大约 10 节课。 这些类放在 header 文件中,它们的完整定义在.cpp文件中。 我以与此代码相同的方式包含这些类:

主.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;
    }
};

当我尝试使用以下命令编译这个 C++ 程序时:

g++ main.cpp CPerson.h

我收到这条消息:

警告:#pragma once 在主文件中

我对此有什么办法吗,或者它只是 g++ 编译器中的错误?

解决了:

您需要编译 only.cpp 文件,其中包含 Class.h 中定义的每个 class 的方法声明

您收到警告是因为您正在编译一个包含#pragma once的文件。 #pragma once只打算在headers中使用,不需要编译headers; 因此警告。 解决方案:不要编译标头。

暂无
暂无

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

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