晚上好
有些人可能认为这是一个愚蠢的问题。但是我已经开始学习 C++,一切都很顺利,直到我遇到这个困扰我好几天的错误。到目前为止,我已经对网络进行了一些研究并修复了所有可能的问题。
问题是,当我尝试包含我制作的新头文件时,编译器无法识别该文件的内容。我正在使用 Dev-C++ 编译器。
当我尝试编译时出现以下错误:main.cpp line 8 error: `test123' undeclared (first use this function)
我有一个名为 001 的文件夹,其中有另一个名为 src 的文件夹(我在其中存储我的 .h 文件),以及 main.cpp 和 new.cpp 。
这是 main.cpp 的代码:
#include <iostream>
#include "src/functions.h"
using namespace std;
int main(){
test123(5,'Test String');
//close on enter keystroke
cin.clear();
cin.ignore(255,'\n');
cin.get();
return 0;
}
这是 functions.h 中的代码:
#ifndef FUNCTIONS_H_INCLUDED
#define FUNCTIONS_H_INCLUDED
string test123(int i,string inputStr);
#endif
这是 functions.cpp 中的代码:
#include "src/functions.h"
string test123(int n, inputStr){
for(int i=0;i<=n;i++){
cout << "\n\t"+inputStr <<endl;
}
}
最佳答案
- 在header中,变量必须声明为
extern
,然后在.cpp
文件中定义。 functions.h
没有#include <string>
提供函数test123
的返回类型- .cpp 文件没有
#include <iostream>
提供cout
。 对于 functions.cpp 中的
inputStr
定义,您没有test123
参数的类型。#ifndef FUNCTIONS_H_INCLUDED #define FUNCTIONS_H_INCLUDED #include <string> extern int testVar; std::string test123(int i, std::string inputStr); #endif
对于 .cpp:
#include <iostream> #include "src/functions.h" using namespace std; int testVar = 123456; string test123(int n, string inputStr){ for(int i=0;i<=n;i++){ cout << "\n\t"+inputStr <<endl; } }
关于c++ - 包含自定义头文件的编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23020682/