I have the following 3 files:
error.h
#ifndef error_h
#define error_h
#include <string>
#include <iostream>
#include <cstdio>
void Error(std::string msg);
#endif
error.cpp
#ifdef error_h
#include "error.h"
void Error(std::string msg)
{
std::cerr
<< "\n=========================================================\n"
<< msg
<< "\n=========================================================\n";
exit(EXIT_FAILURE);
}
#endif
foobar.cpp
#include "error.h"
int main()
{
for(int i=0; i<99; i++)
if(i==55)
Error("this works");
return 0;
}
Now I do:
$ g++ -c error.cpp foobar.cpp
$ g++ error.o foobar.o -o exampleprogram
And I get:
foobar.o: In function `main':
foobar.cpp:(.text+0x4b): undefined reference to `Error(std::basic_string<char,
std::char_traits<char>, std::allocator<char> >)'
collect2: ld returned 1 exit status
What am I doing wrong? What do I need to understand to resolve this, and similar issues in the future without asking questions? Thanks!
Why do you have these lines in error.cpp?
Since the preprocessor symbol
error_his not defined the entire contents of error.cpp are being omitted by the preprocessor. Remove those lines and your program will link successfully.You seem to have a misunderstanding of how (and maybe why)
#includeguards are to be used. Refer to this answer for an explanation.Also, there’s no need to include iostream and cstdio in error.h, since that file is not using anything declared in either of those headers. Those files should be included in error.cpp.