0

I have a function, field or etc.(let's call it symbol a) that is declared in file A.h, this a is used in file B.h, so B.h includes A.h. But A.h uses another function, field or etc.(let's call it symbol b) from B.h, so A.h includes B.h. Theoretically it's allowed to work because these symbols may not be variables that stores each other or functions that calls each other making infinity "recursion". But it doesn't work.

There is a real life example of what I try to say. I didn't include in it all irrelevant details and separation of declaration and implementation in two files.

File Application.h:

#ifndef APP_H
#define APP_H

#include "Log.h"

class Application
{
public:
    static void exception(std::string description)
    {
        Log::print("Program throwed: " + description);
        throw description;
    }
};

#endif // APP_H

File Log.h:

#ifndef  LOGG_H
#define LOGG_H

#include "Application.h"
#include <string>
#include <iostream>

class Log
{
public:
    static void print(std::string message)
    {
        if (message.size() > 200)
        {
            Application::exception("Message is too long");
        } else
        {
            std::cout << __TIME__ << " >> \t " << message << std::endl;
        }
    }
};

#endif // LOGG_H

File Main.h:

#include "Application.h"
#include "Log.h"

int main()
{   
 Log::print("TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT");
    // There are over 200 charcaters. Then it will call method Application::exception from Log::print

    return 1;
}

Result:

C2653 on line 17(Application::exception("Message is too long");) in file Log.h:

Application: is not a class or namespace name

C3861 on line 17(Application::exception("Message is too long");) in file Log.h:

exception: identifier not found

user11655900
  • 420
  • 7
  • 15
  • What you're describing, I believe, is [circular dependency](https://stackoverflow.com/q/625799/10077). – Fred Larson Sep 13 '19 at 21:38
  • You have a circular include. This means one of the headers is not available when the other needs it. Normally you avoid this by forward declaring one types or abstracting it away behind a header both can safely include. In this case, rather than throwing an exception, truncate the too-long message. What's the log user gonna do? Go , "My bad." and try again with a shorter log message? If you want to catch people writing too-long messages during development, use an `assert`, crash the program, and mock them in the lunchroom for breaking the build. – user4581301 Sep 13 '19 at 21:38

1 Answers1

1

You need to break the include cycle.

Move the code from one of the header into the matching .cop file. Remove the #include from the header. Move it to .cpp file.

Forward-declare as needed.

Jeffrey
  • 11,063
  • 1
  • 21
  • 42