简体   繁体   中英

C++ redefinition with include guard and #pragma once

So I'm new to the concept of header files. As far as I understand stuff gets defined in the header and then implemented/used in the *.cpp file. It now cannot build and is giving me Semantic Issues "redefinition of '//*literally everything*//'"

What I do now is

//move.hpp
#pragma once
#ifndef MOVE_HPP
#define MOVE_HPP

#include <stdio.h>

class Move
{
    private:
        int stolen;

    public:
        Move(int _stolen);
        int get_stolen();
};
#endif /* move_hpp */


//----------------------------------------

//move.cpp
#include "move.hpp"

int Move::get_stolen()
{
    return stolen;
}
Move::Move(int _stolen)
{
    this->stolen = _stolen;
}

So what I am doing here is saying what variables and functions Move has, right? Well, I copied my approach more or less from a post describing how to use headers, yet in the move.cpp i get a "Redifinion of 'functionname'" for all of my methods where I give them a body in the *.cpp. So my question is: Am I using headers right and what am I to do to fix the Redefinition error?

edit: when I wrote this I forgot i included this file somwhere else, when I remove that include I don't have any issues but the now used objects that don't exist without the inclide

Technically, you do not need to use #pragma once and #ifndef.. #define... #endif together. They are the same algorithms for compiling the header file only once , I never encountered the problem myself, but for the purpose of multiplatforming and compiling without errors - I would use the latter ( #ifndef.. and #endif ) only.

About the header, it is written good. The purpose of the header is to declare the class variables and member functions. And, of the.cpp is to define. That is why they are called declaration and definition files, respectively. And it seems that you did it right. Only make sure to include only the.hpp in your main.cpp , to prevent the redefinition error.

EDIT: Note, if it is of any help, that C++ accepted header files are: .h, .hpp, .hh and definition types are: .C, .cc, .cpp.

the.hpp files are files that are copied by the #include preprocessor instruction. You need to avoid copying it many times (otherwise you would have multiple function definitions, which will lead to compilation issues).

The #pragma once (put this file only once, only works in c++) is equivalent to the #ifndef (if constant not defined, then put the rest of the code), #define (defines it so it would not copy the file a second time) and the #endif (finis of conditional copy)

you can check the output of preprocessor using g++ -E option to stop before compiling, or gcc -E (for c compiling)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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