Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

c++ - Header guards do not seem to work?

I have declared some constant variable in seperate header (i.e., constant.h).

I include the constant.h in my debug.cpp as to access the variable.

I include the constant.h, debug.h in my main.cpp as to access the variable.

When I compile, the error it shows **multiple definition** of **IF_DEBUG_ENABLED**.

Kindly tell me what is actually I'm doing wrong. Also, please note that this is my first day on my very first c/c++ application. I've never even read it in school.

My code source is as follows: as

/-- constant.h --/

#ifndef CONSTANT_H
#define CONSTANT_H

const char* APP_NAME            = "ymcmcb";
const bool  IF_DEBUG_ENABLED    = true;

#endif // CONSTANT_H

/-- debug.h --/

#ifndef DEBUG_H
#define DEBUG_H

#include <QString>

class Debug
{  
public:
    static void Log(QString Message);
};

#endif // DEBUG_H

/-- debug.cpp --/

#include "constant.h"
#include "debug.h"

#include "QDebug"

static void Log(QString Message)
{
    if (IF_DEBUG_ENABLED)
        qDebug() << Message;    //It says problem is here
}

/-- main.cpp --/

#include "constant.h"
#include "debug.h"

int main(int argc, char *argv[])
{
    Debug::Log("New application has been run");
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should put the definition in a .cpp file, not in a header. In the header you should only put declarations : extern const bool IF_DEBUG_ENABLED; This will tell any code #includeing it that there exist some global variable named IF_DEBUG_ENABLED. Inside debug.cpp you should put the actual definition.

The guards only help to prevent you from defining multiple times in a single compilation unit. But you have two compilation units: debug.cpp (plus headers) and main.cpp (plus headers). which means you have multiple definitions of the variables in the header.


You have another problem: you implement a static function Log() but you should implement a static class-method Debug::Log().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...