简体   繁体   中英

Basic C++ Redefinition Error

I've been reading about header guards and and their use to solve redefinition errors, but I'm not quite sure how to implement it properly. Here's an simplified example of what I'm trying to do:

fileA.h

#include first_header.h
#include second_header.h

// code here

fileB.h

#include first_header.h
#include second_header.h

// code here

mainfile.cpp

#include fileA.h
#include fileB.h

// code here

Now the problem comes in the mainfile.cpp since I need to include both the fileA.h and fileB.h headers, but each of these contains the same header references thus giving me the redefinition error. I'm not really sure how to get around it or implement the header guards properly in this scenario.

Logic: Check if specific macro is defined, if the macro is not defined, define it and include the content of the header file. This will prevent from duplicated inclusion of the header content.

Like this:

file A:

#ifndef fileA_h
#define fileA_h

#include first_header.h
#include second_header.h

//code here

#endif

file B:

#ifndef fileB_h
#define fileB_h

#include first_header.h
#include second_header.h

//code here

#endif

First of all, you need to put either quotes or angle brackets around the filenames, like this: #include <fileA.h> or #include "fileA.h"

From what you've posted, it looks like you don't really understand how header guards work. So here's the rundown.

Let's say I have a function that I want to be able to call from different c++ files. You first need a header file. (You can do includes from inside your include guard.)

#ifndef MYHEADER_HPP
#define MYHEADER_HPP

#include "first_header.h"
#include "second_header.h"

void MyFunction();

#endif

The non-include preprocessor lines make up what is called an "Include Guard," and you should always guard your header files.

You then implement said function in a .cpp file, like this:

#include "MyHeader.hpp"

void MyFunction()
{
    // Implementation goes here
}

Now, you can use this function in other code:

#include "MyHeader.hpp"

int main()
{
    MyFunction();
}

If you're using an IDE compiling and linking is handled for you, but just in case, you can compile and link like this using g++ (assuming a "main.cpp" file and a "MyFunction.cpp" file):

g++ main.cpp -c
g++ MyFunction.cpp -c
g++ main.o MyFunction.o -o MyExecutable

I hope this helps and good luck!

Most compilers (eg Visual Studio) also support #pragma once which can be used instead of include guards expressed as "#ifndef". You will find that in some legacy code written with MS Visual C++.

However, the

#ifndef MYHEADER_HPP
#define MYHEADER_HPP

// code here

#endif

is more portable.

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