c++ - 包含自定义头文件的编译器错误

标签 c++ dev-c++

晚上好

有些人可能认为这是一个愚蠢的问题。但是我已经开始学习 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;
    }
}

最佳答案

  1. 在header中,变量必须声明为extern,然后在.cpp文件中定义。
  2. functions.h没有#include <string>提供函数test123的返回类型
  3. .cpp 文件没有#include <iostream> 提供cout
  4. 对于 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/

相关文章:

c - 开发 C++ 与 OpenCV 崩溃

C++ 结构错误 - 错误 C2061 : syntax error : identifier

compiler-errors - 为什么我的第一个使用dev-c++的程序无法正常工作?

c++ - g++ 编译选项

c++ - 如何解决错误 193 :%1 is not a win32 application in dev c++?

c++ - 为什么 Rust 需要 C++ 工具链来生成 Rust 二进制文件,而像 Go 这样的语言没有这个要求?

c++ - VS2013编译链接ngspice作为共享库

c++ - () 运算符重载 C++

C++11 可重入类锁定策略

c++ - Base64解码: How to get the data