简体   繁体   English

编译器/链接器错误“未定义的引用”

[英]Compiler/linker error “undefined reference”

Hi I am just starting to learn C++. 嗨,我刚开始学习C ++。 I bought this big C++ for Dummies book and have been going through it. 我为Dummies书买了这个大C ++,并且经历过它。 Its been really interesting so far but now I am stuck. 到目前为止它真的很有趣,但现在我被卡住了。 I have been googling this problem, but to no avail. 我一直在谷歌搜索这个问题,但无济于事。 I am using I am using codeblocks 10.05 with GNU GCC. 我正在使用我使用的代码块10.05与GNU GCC。

I keep getting an error that says: 我一直收到错误消息:

In function 'main':
undefined reference to 'SafeCracker(int)'

The code isn't complicated. 代码并不复杂。 I am just new and am extremely frustrated. 我只是新人,非常沮丧。 I don't want to skip over this part; 我不想跳过这一部分; I want to know what is going on. 我想知道发生了什么。

Main: 主要:

#include <iostream>
#include "safestuff.h"

using namespace std;

int main()
{
  cout << "Surprise, surprise!" << endl;
  cout << "The combination is (once again)" << endl;
  cout << SafeCracker(12) << endl;
  return 0;
}

Function: 功能:

#include <iostream>

using namespace std;

string SafeCracker(int SafeID)
{
    return "13-26-16";
}

Header: 标题:

using namespace std;

#ifndef SAFESTUFF_H_INCLUDED
#define SAFESTUFF_H_INCLUDED

 string SafeCracker(int SafeID);

#endif // SAFESTUFF_H_INCLUDED

You are not compiling the second file you listed along with the first one. 您没有编译第一个列出的第二个文件。 Try compiling directly with gcc to understand this. 尝试直接用gcc编译来理解这一点。

assuming your files are named: 假设您的文件命名为:

  • main.cpp main.cpp中
  • SafeCracker.cpp SafeCracker.cpp
  • safestuff.h safestuff.h

This is what you are doing 这就是你在做什么

gcc main.cpp

While you should be doing this 虽然你应该这样做

gcc main.cpp SafeCracker.cpp

Also, SafeCracker.cpp should be including the header file as well, just for clarity. 此外,SafeCracker.cpp也应该包含头文件,只是为了清楚起见。 Any reasons why you have them separated? 你将它们分开的原因是什么?

On another note, from seeing Daniel Hu's answer, <iostream> is automatically including <string> for you. 另一方面,从看到Daniel Hu的回答, <iostream>会自动包含<string> You should not depend on this functionality, and should instead include <string> in each file that uses strings. 您不应该依赖此功能,而应该在每个使用字符串的文件中包含<string>

(From comment below) You're probably trying to build your main.cpp as a stand-alone file. (来自下面的评论)您可能正在尝试将main.cpp构建为独立文件。 This will leave SafeCracker.cpp uncompiled. 这将使SafeCracker.cpp无法编译。 What you need is create a project in Codeblocks and add all three files to it (both *.cpp files as well as the *.h file). 您需要的是在Codeblocks中创建一个项目并将所有三个文件添加到它(* .cpp文件以及* .h文件)。

I think it's because you did not #include <string> 我认为这是因为你没有#include <string>

C++ has to import the string library to use strings or else everything is treated as char arrays. C ++必须导入字符串库才能使用字符串,否则所有内容都被视为char数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM