在main.cpp
中,我不断收到错误消息,指出print
未定义(以及此类其他错误。
我在名为“misc”的头文件下定义了print()
misc.h
#include <iostream>
#include <cstdlib>
#include <fstream>
#define MISC_H
#ifndef MISC_H
void print(string str) { cout << str << endl; }
string userIn(string prompt = "Option:") { //For collecting user responses
string response;
print(prompt);
cin.clear();
cin.sync();
getline(cin, response);
if (!cin) { response = "wtf"; }
else if (response == "512") { //Secret termination code
print("Program terminated");
exit(0);
}
print("");
return response;
}
#endif
然后在main.cpp
我#include Headers/misc.h"
(标题文件位于单独的文件夹中)
我在这里做错了吗?
答案 0 :(得分:2)
在不知道您正在使用的编译命令的情况下,我看到的是“include guard”不正确。
第一个命令#define MISC_H
将使宏开始存在。
之后,当你致电#ifndef MISC_H
时,它总是假的,因为你刚刚定义了它,结果是这个文件的来源总是被丢弃。
您需要将这些行翻转为:
#ifndef MISC_H
#define MISC_H
答案 1 :(得分:1)
您的#ifndef
和#define
订单错误。它应该是:
#ifndef MISC_H
#define MISC_H
最好在文件顶部之前包含其他内容。
答案 2 :(得分:0)
永远不会到达#ifndef MISC_H ... #endif
块。 MISC_H就在此之前定义,因此它永远不会在那里传递if条件,因此从未定义打印函数。
这样做:
#ifndef MISC_H
#define MISC_H
//Now define what you want to define
虽然您可以完全省略这些内容并使用#pragma once
代替,但如果可用的话。