Compiler/linker error "undefined reference"

c++, codeblocks, linker-errors

Solution

You are not compiling the second file you listed along with the first one. Try compiling directly with gcc to understand this.

assuming your files are named:

- main.cpp

- SafeCracker.cpp

- 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. Any reasons why you have them separated?

On another note, from seeing Daniel Hu's answer, `<iostream>` is automatically including `<string>` for you. You should not depend on this functionality, and should instead include `<string>` in each file that uses strings.

(From comment below) You're probably trying to build your main.cpp as a stand-alone file. This will leave SafeCracker.cpp uncompiled. 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).

Problem

Hi I am just starting to learn C++. I bought this big C++ for Dummies book and have been going through it. 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. 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 ```

Original source