Score:-1

C++ Undefined reference to a function

ng flag

I am using ubuntu 16.04 When I try to compile the program with

g++ -g main.cpp -o main

This is my g++ version

g++ --version
g++ (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 status

main.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);
   
};

#endif

Helper.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

Score:2
hr flag

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 main

or (for simple programs) do it all in one step

g++ -g main.cpp Helper.cpp -o main
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.