简体   繁体   中英

Why could a #define be causing problems in a header?

I've only recently got started with C++ and tried to build a simple class using different files (main, header and implementation). While doing that, I ran into a very strange (well, for me, at least) problem with #ifndef / #define. I'll show the code first:

// main.cpp :
#include <iostream>
#include "daytime.h"

using namespace std;

int main(int argc, char** argv) {
    DayTime sT = DayTime(75);
    cout << sT.getMin();

    return 0;
}

// daytime.h :
#ifndef DayTime
#define Daytime

class DayTime
{
    int min;

    public:
        DayTime(int min);
        int getMin();
        int getHour();
};

#endif

// daytime.cpp :
#include "daytime.h"

DayTime::DayTime(int min)
    : min(min) {}

DayTime::getMin()
{
    return this->min;
}

DayTime::getHour()
{
    return int (this->min / 60);
}

As you can see, there is a typo in #define Daytime in daytime.h - 'time' is written with a lowercase 't'. And here comes the strange part: as long as that typo is there , the program compiles and runs without problems. But the moment I correct it to #define DayTime , with uppercase 'T', it no longer complies and I get a multitude of errors:

2   0   main.cpp    In file included from main.cpp
9   11  daytime.h   [Error] expected unqualified-id before 'int'
9   11  daytime.h   [Error] expected ')' before 'int'
5   1   daytime.h   [Error] an anonymous struct cannot have function members
12  1   daytime.h   [Error] abstract declarator '<anonymous class>' used as declaration
D:\Dokumentumok\Prog\C++\Test\main.cpp  In function 'int main(int, char**)':
7   10  main.cpp    [Error] 'sT' was not declared in this scope
28      Makefile.win    recipe for target 'main.o' failed

I've been wasting hours on this by now, but I've always got back to this same issue: typo there, it works, typo gone, it doesn't - and I just don't get it. So I'd be very grateful for some assistance here.

#define DayTime causes any future occurrences of DayTime to be replaced with the empty string.

So the name of your class in class DayTime (and its constructor) are getting deleted, causing issues: the compiler effectively sees:

class
{
    int min;

    public:
        (int min);
        int getMin();
        int getHour();
};

Usually for this exact reason, when people make these include guards, they use something that is unlikely to show up as a real identifier. For example:

#ifndef DAYTIME_H
#define DAYTIME_H

class DayTime {
  // blah blah blah
};

#endif

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