I have a question regarding c++ cross-reference error (beginner)

Asked 2 years ago, Updated 2 years ago, 24 views

c++

2022-09-22 14:43

1 Answers

It's about cross-reference and header guard.

If you look at the header file you uploaded, there is no header guard. Header Guard is responsible for ensuring that the contents of the included headers are not duplicated in many places. Without a header guard, the preprocessor is pasted into that position whenever a header is included.

Main Menu.h and SubMenu.h is including each other. That means Main Menu.If h is included, SubMenu.h is included, SubMenu.h included MainMenu.Include h and Main Menu.SubMenu because it becomes h.The h operation will be carried out indefinitely.

Therefore, the C1014 error you mentioned (there are too many files included). Level = 1024) error.

To solve this problem, it is necessary to add the header guard mentioned earlier. There are many ways to add header guards, but the simplest way is to enter #pragmaence in the first line of the header. This method is not standard, but is actually standard and is available for most compilers.

So please add header guard as below.

#pragam once
// ...

In C++, classes that do not complete definitions are not immediately available.

The SubMenu1 class must be defined for the MainMenu class to be defined. For the SubMenu1 class to be defined, the MainMenu class must be defined. However, C++ will fail because classes that are not defined cannot be used immediately.

There are several ways to resolve this issue: forward declaration, order header addition, and hide dependencies through cpp isolation.

Fortunately, the two classes you created do not refer to each other with member variables, so it is an easy step to solve.

First, create MainMenu.cpp and SubMenu.cpp. Then move the definitions of the two classes of member functions to each cpp file. And Main Menu.h and SubMenu.You can also move the code that includes each other in h to each cpp.

If you write it briefly, it's as follows.

// MainMenu.h
#pragma once

#include <iostream> 
// ...
class MainMenu {
// ...
};
// MainMeny.cpp
#include "MainMenu.h"
#include "SubMenu.h"

Mainmenu::Mainmenu(string m1, string m2, string m3) {
// ...
}
// ...
// SubMenu.h
#pragma once

#include <iostream> 
// ...
class SubMenu1 {
// ...
};
// SubMeny.cpp
#include "SubMenu.h"
#include "MainMenu.h"

Submenu1::Submenu1(string s1, string s2, string s3) {
// ...
}
// ...


2022-09-22 14:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.