C++ Undefined reference to a function
By James Williams
I am using ubuntu 16.04 When I try to compile the program with
g++ -g main.cpp -o mainThis is my g++ version
g++ --versiong++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.I get this compilation error
main.cpp:8: undefined reference to `Helper::IsStringNumeric(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
collect2: error: ld returned 1 exit statusmain.cpp:
#include "Helper.h"
#include <iostream>
#include <vector>
int main()
{ std::cout << Helper::IsStringNumeric("200");
}Helper.h
#ifndef HELPER_H
#define HELPER_H
#include <vector>
#include <string>
class Helper
{
private: /* data */
public: static bool IsStringNumeric(const std::string &str);
};
#endifHelper.cpp
#include "Helper.h"
#include <string>
#include <algorithm>
bool Helper::IsStringNumeric(const std::string &str)
{ std::string::const_iterator iterator = str.begin(); while (iterator != str.end() && std::isdigit(*iterator)) { ++iterator; } return !str.empty() && iterator == str.end();
}My cpp and header files seem right , So I am not sure why I am getting errors
01 Answer
Adding #include "Helper.h" to your main.cpp makes the declaration of Helper::IsStringNumeric visible to the compiler, but you still need to compile Helper.cpp to object code in order to make the definition of Helper::IsStringNumeric available when you link your main program.
You can either compile each translation unit to an object code file and then link them:
g++ -g -o main.o -c main.cpp
g++ -g -o Helper.o -c Helper.cpp
g++ main.o Helper.o -o mainor (for simple programs) do it all in one step
g++ -g main.cpp Helper.cpp -o main