Undefined reference to ошибка

C++ undefined reference linker error often pops up when building large code bases, so you can learn how to track them down quickly and rectify the cause here.

C undefined reference errorC++ undefined reference is a linker error that often may come up when the function is declared but not implemented. These errors are usually partly identified by the linker error messages, but a programmer still needs to manually investigate the code, build system or linked libraries.

In the following article, we will mostly focus on the causes that occur in source code rather than in the build process or during library linkage. Find out the details in the upcoming paragraphs.

What Does Undefined Reference Mean in C++?

Undefined reference means that the linker is not able to find a symbol definition in any object file, but it’s still referenced. Undefined reference error is not C++ language-specific but rather a result of the executable program generation process. The latter process roughly works as follows: the compiler translates the human-readable source code into machine instructions and generates objects files. Then, the linker will try to combine all needed object files to generate an executable program or, alternatively, a library.

The linker itself can be considered as standalone software which deals with the object files and symbols defined in them. Symbols represent different entities like global variables, function names, member function names, etc.

In the following example, we have a SampleClass class that declares a constructor member. The only thing missing is that no definition is provided. So, if we try to build this program, the linker will throw an undefined reference error related to SampleClass::SampleClass() symbol.

– Code:

#include <iostream>
using std::string;
class SampleClass {private:
string user;
string name;
int number;public:
SampleClass();
};
int main() {
SampleClass sp1;
return 0;
}

– Program Output:

/usr/bin/ld: /tmp/ccoWSfKj.o: in function `main’:
tmp.cpp:(.text+0x24): undefined reference to `SampleClass::SampleClass()’
/usr/bin/ld: tmp.cpp:(.text+0x35): undefined reference to `SampleClass::~SampleClass()’
collect2: error: ld returned 1 exit status

How To Fix Undefined Reference in C++

You can fix undefined reference in C++ by investigating the linker error messages and then providing the missing definition for the given symbols. Note that not all linker errors are undefined references, and the same programmer error does not cause all undefined reference errors.

However, it’s more likely to be function-related when it’s declared somewhere, but the definition is nowhere to be found. The issue in the previous example code can be very easily traced as the program is very small.

On the other hand, huge codebases can yield undefined reference errors that may be harder to track down. The next code snippet tries to demonstrate a similar scenario which generates quite a large output of errors from the linker. Notice that the error comes from the polymorphic class SampleClass, which declares PrintContents() as a virtual function.

However, it does not even include empty curly braces to denote the body and qualify for the definition, resulting in an undefined reference error.

– Code:

#include <iostream>
#include <utility>
#include <sstream>using std::cout;
using std::endl;
using std::string;
class SampleClass {
private:
string user;
string name;
int number;public:
SampleClass(string  u, string  n, int num) :
user{std::move(u)}, name{std::move(n)}, number{num} {};
SampleClass(string  u, int num) :
user{std::move(u)}, name{“Name”}, number{num} {} ;virtual string PrintContents() const;
string getName() const;
string getUser() const;
int getNumber() const;
};
class DerivedClass : public SampleClass {
string identifier;public:
DerivedClass(string u, string n, int num, std::string id) :
SampleClass(std::move(u), std::move(n), num),
identifier{std::move(id)} {};
string PrintContents() const override;
string getIdentifier() const;
};
string DerivedClass::getIdentifier() const {
return this->identifier;
}
string DerivedClass::PrintContents() const {
std::stringstream ss;
ss << “user: ” << this->getUser()
<< ” name: ” << this->getName()
<< ” number: ” << this->getNumber()
<< ” identifier: ” << this->identifier  << ‘n’;
return ss.str();
}
string SampleClass::getName() const {
return this->name;
}
string SampleClass::getUser() const {
return this->user;
}
int SampleClass::getNumber() const {
return this->number;
}
void print(SampleClass& sp) {
cout << sp.PrintContents();
}
int main() {
auto dc1 = DerivedClass(“it”, “ai”, 5122, “tait”);
print(dc1);
return 0;
}

– Program Output:

/usr/bin/ld: /tmp/cckqLhcA.o: in function `SampleClass::SampleClass(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, int)’:

tmp.cpp:(.text._ZN11SampleClassC2ENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES5_i[_ZN11SampleClassC5ENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES5_i]+0x1f): undefined reference to `vtable for SampleClass’
/usr/bin/ld: /tmp/cckqLhcA.o: in function `SampleClass::~SampleClass()’:
tmp.cpp:(.text._ZN11SampleClassD2Ev[_ZN11SampleClassD5Ev]+0x13): undefined reference to `vtable for SampleClass’
/usr/bin/ld: /tmp/cckqLhcA.o:(.data.rel.ro._ZTI12DerivedClass[_ZTI12DerivedClass]+0x10): undefined reference to `typeinfo for SampleClass’
collect2: error: ld returned 1 exit status

Undefined Reference in Programs Without Main Function

Undefined reference error can occur if you try to compile the source code file that does not have the main() function. To be more precise, these types of source files will yield linker errors if compiled with the usual compiler arguments.

If you intend to compile a given source file without the main() function, you should pass the special argument to not run the linker stage. The latter is usually achieved with a -c argument to the compiler command (e.g., g++ or clang++ ).

– Code:

#include <iostream>
#include <utility>
#include <sstream>using std::cout;
using std::endl;
using std::string;
class SampleClass {private:
string user;
string name;
int number;public:
SampleClass(string  u, string  n, int num) :
user{std::move(u)}, name{std::move(n)}, number{num} {};
SampleClass(string  u, int num) :
user{std::move(u)}, name{“Name”}, number{num} {} ;
virtual string PrintContents() const;string getName() const;
string getUser() const;
int getNumber() const;
};
class DerivedClass : public SampleClass {
string identifier;
public:
DerivedClass(string u, string n, int num, std::string id) :
SampleClass(std::move(u), std::move(n), num),
identifier{std::move(id)} {};
string PrintContents() const override;
string getIdentifier() const;
};
string DerivedClass::getIdentifier() const {
return this->identifier;
}
string DerivedClass::PrintContents() const {
std::stringstream ss;
ss << “user: ” << this->getUser()
<< ” name: ” << this->getName()
<< ” number: ” << this->getNumber()
<< ” identifier: ” << this->identifier  << ‘n’;
return ss.str();
}
string SampleClass::getName() const {
return this->name;
}
string SampleClass::getUser() const {
return this->user;
}
int SampleClass::getNumber() const {
return this->number;
}
void print(SampleClass& sp) {
cout << sp.PrintContents();
}

– Program Output:

/usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/10/../../../x86_64-linux-gnu/Scrt1.o: in function `_start’:
(.text+0x24): undefined reference to `main’
collect2: error: ld returned 1 exit status

Tracking Down Undefined Reference Errors in Derived Classes

Another useful method to easily track down undefined reference errors in large codebases is enabling compiler warnings. Sometimes these may warn that functions are referenced but never defined. In the following example, the derived class explicitly overrides a virtual function but does not provide an implementation. Note that these types of errors may also be caused when the program build script or file does not include the corresponding source file.

– Code:

#include <iostream>
#include <utility>
#include <sstream>
#include “tmp.h”using std::cout;
using std::endl;
using std::cin;
using std::string;class SampleClass {
private:
string user;
string name;
int number;
public:
SampleClass(string  u, string  n, int num) :
user{std::move(u)}, name{std::move(n)}, number{num} {};
SampleClass(string  u, int num) :
user{std::move(u)}, name{“Name”}, number{num} {} ;
virtual string PrintContents() const { return {}; };string getName() const;
string getUser() const;
int getNumber() const;
};
class DerivedClass : public SampleClass {
string identifier;
public:
DerivedClass(string u, string n, int num, std::string id) :
SampleClass(std::move(u), std::move(n), num),
identifier{std::move(id)} {};
string PrintContents() const override;
string getIdentifier() const;
};
string DerivedClass::getIdentifier() const {
return this->identifier;
}
string SampleClass::getName() const {
return this->name;
}
string SampleClass::getUser() const {
return this->user;
}
int SampleClass::getNumber() const {
return this->number;
}
void print(SampleClass& sp) {
cout << sp.PrintContents();
}
int main() {
auto dc1 = DerivedClass(“it”, “ai”, 5122, “tait”);
print(dc1);
return 0;
}

– Program Output:

/usr/bin/ld: /tmp/ccdcAqfb.o: in function `DerivedClass::DerivedClass(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)’:

tmp.cpp:(.text._ZN12DerivedClassC2ENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES5_iS5_[_ZN12DerivedClassC5ENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES5_iS5_]+0xa6): undefined reference to `vtable for DerivedClass’
/usr/bin/ld: /tmp/ccdcAqfb.o: in function `DerivedClass::~DerivedClass()’:

tmp.cpp:(.text._ZN12DerivedClassD2Ev[_ZN12DerivedClassD5Ev]+0x13): undefined reference to `vtable for DerivedClass’
collect2: error: ld returned 1 exit status

Key Takeaways

In this article, we covered common reasons that yield an undefined reference to C++ function errors and described several ways to identify them. Here are some key points to bear in mind:

  • Undefined reference error is thrown by the linker rather than the compiler
  • It’s usually caused by the reference to the function that has been declared, but a definition can’t be found
  • Investigate linker error messages which can help to pin down the identifiers that are related to the cause of the problem
  • Don’t run the linker stage on programs that don’t include the main function

How to fix undefined reference in cNow you should be able to move on to some practical problems of analyzing linker errors and fixing them. You are definitely ready to try manually building relatively medium programs with multiple files and investigate possible causes for linker errors.

  • Author
  • Recent Posts

Position is Everything

Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.

Position is Everything

This post will explain C++ Errors’ undefined reference to. We will go over the crucial mistakes that we frequently encounter in C++ that are equally vital. Apart from the system and semantic error’s and exceptions that happen from time to time, we likewise get other critical errors that affect programs’ running.

These mistakes mostly take place towards the completion of the program at runtime. Sometimes the program provides the correct output, and then the error takes place.

In this article, you can know about undefined reference to here are the details below;

What You Will Learn: [program] Important C++ Errors

In this tutorial, we will discuss three kinds of mistakes that are critical from any C++ developer’s perspective.

  • – Undefined reference
  • – Segmentation fault (core dumped).
  • – Unresolved external symbol.

We will go over the possible causes of each of these errors and the safety measures that we can take as a programmer to prevent these errors.

Let’s begin!!

Undefined Reference.

An “Undefined Reference” error’s occurs when we have a reference to an object name (class, function, variable, and so on) in our program, and the linker cannot find its definitions when it tries to search for it in all the related item files and libraries. You can also check another post like how to fix 0xc1900101.

Thus, when the linker cannot find a related item’s meaning, it releases an “undefined reference” error. As clear from the definition, this error happens in the later stages of the linking procedure. Numerous factors cause an “undefined reference” mistake.

We discuss some of these factors below:

# 1) No Definition Provided For Object.

This is the most essential factor for causing an “undefined reference” mistake. The programmer has just forgotten to define the item.

Consider the following C++ program. Here we have just specified the model of function and then utilized it in the main function.

#include

int func1();.

int main().

Output.

So when we compiles this program, the linker error states “undefined reference to ‘func1()’” is released.

To get rid of this mistake, we fix the program as follows by providing the meaning of the function func1. Now the program offers the appropriate output.

#include using namespace sexually transmitted disease.

int func1();.

int main().

func1();.

int func1()

cout<<” hello, world!!”;.

Output:

Hi, world!!

# 2) Wrong Definition (signatures do not match) Of Objects Used.

Yet another cause for “undefined reference” mistake is when we specify wrong meanings. We use any item in our program, and its meaning is something different.

Think about the following C++ program. Here we have phoned to func1 (). Its prototype is int func1 (). However, its meaning does not match with its model. As we see, the meaning of the function includes a specification to the function.

Therefore when the program is put together, the collection succeeds because of the prototype and function call match. But when the linker attempts to connect the function call with its definition, it finds the problems and issues the error as “undefined reference”.

#include

using namespace std;.

int func1();.

int primary().

int func1( int n)

Output:

Thus to prevent such errors, we merely cross-check if the definitions and use of all the things match our program.

# 3) Object Files Not Linked Properly.

This issue can also trigger the “undefined reference” error. Here, we might have more than one source files, and we might assemble them independently. When this is done, the items are not connected correctly, leading to “undefined reference”.

Think about the following two C++ programs. In the first file, we use the “print ()” function, defined in the 2nd file. When we put together these files separately, the first file offers “undefined reference” for the print function, while the 2nd file gives “undefined reference” for the main function.

int print();.

int primary().

Output:

int print()

return 42;.

Output:

The method to solve this error is to assemble both the files all at once (For example, by utilizing g++).

Apart from the causes already discussed, “undefined reference” might likewise occur for the following reasons.

# 4) Wrong Project Type.

When we specify incorrect project types in C++ IDEs like the visual studio and try to do things that the task does not expect, we get “undefined reference”.

# 5) No Library.

Suppose a programmer has not defined the library course properly or completely forgotten to define it. In that case, we get an “undefined reference” for all the references the program utilizes from the library.

# 6) Dependent Files Are Not Compiled.

A developer has to make sure that we assemble all the project dependencies in advance so that when we assemble the job, the compiler discovers all the dependencies and assembles them successfully. If any of the dependencies are missing out on, then the compiler offers “undefined reference”.

Apart from the cases discussed above, the “undefined reference” error can occur in lots of other situations. However, the bottom line is that the developer has got things incorrect, and to avoid this mistake, they must be corrected.

Division Fault (core disposed).

The mistake “segmentation fault (core discarded)” is an error that shows memory corruption. It usually takes place when we try to access a memory that does not belong to the program into factor to consider.

Here are some of the reason’s that trigger the Segmentation fault mistake.

# 1) Modifying The Constant String.

Think about the following program wherein we have stated a constant string. Then we attempt to modify this consistent string. When the program is performed, we get the mistake displayed in the output.

#include

int primary().

Output:

# 2) Dereferencing Pointer.

A guideline needs to indicate a valid memory place before dereference it. In the below programs, we see that the guideline indicates NULL, which suggests the memory location it’s indicating is 0, i.e. void.

Thus when we dereference it in the next line, we are, in fact, trying to access its unknown memory location. This undoubtedly leads to a division fault. Also, check how to fix hulu proxy error.

#include

utilizing namespace std;.

int main().

Here we are accessing an unidentified memory place.

* ptr = 1;.

cout << * ptr;.

return 0;.

Output:

Division fault.

The next program reveals a comparable case. In this program, likewise, the tip is not indicating valid data. An uninitialized pointers is as good as NULL, and for this reason, it likewise points to an unknown memory location. Therefore when we try to dereference it, it leads to a segmentation fault.

#include using namespace sexually transmitted disease;

int primary().

Int * p;

cout<< * p;.

return 0;.

Output:

Segmentation fault.

In order to avoid such errors, we have to ensure that our tip variables in the program indicate valid memory locations always.

# 3) Stack Overflow.

When we have recursive contact our program, they eat up all the memory in the stack and cause the stack to overflow. In such cases, we get the division fault as lacking stack memory is also a kind of memory corruption.

Consider the below program where we compute the factorial of a number recursively. Keep in mind that our base condition tests if the number is 0 and then returns 1. This program works perfectly for positive numbers.

However, what happens when we actually pass a negative number to a factorial function? Well, as the base condition is not offered for the negative numbers, the function doesn’t know where to stop and thus results in a stack overflow.

This is displayed in the output below that offers division fault.

#include

using namespace std;.

int factorial( int n).

if( n == 0).

return factorial( n-1) * n;.

int main().

cout<< factorial( -1 );.

Output:

Segmentation fault (core dumped).

Now in order to repair this mistake, we slightly alter the base condition and also specify the case for unfavourable numbers as revealed below.

#include

utilizing namespace std;.

int factorial( int n).

What about n < 0?

if( n <= 0).

Return 1;

return factorial( n-1) * n;.

int main().

cout<<” Factorial output:”<< factorial( -1 );.

Output:

Factorial output:1.

Now we see that the division fault is looked after, and the program works fine.

Unresolved External Symbol.

The unresolved external symbols is a linker error that indicates it can not discover the symbol or its referral during the connecting process. The mistake is similar to “undefined reference” and is provided interchangeably.

We have actually provided two circumstances below where this error can happen.

# 1) When we refer to a structure variable in the program which contains a static member.

#include

struct C

static int s;.

;.

// int C:: s;// Uncomment the following line to repair the mistake.

int primary()

Output:

In the above programs, structure C has a fixed member s that is not accessible to the outside programs. So when we attempt to designate it worth in the main function, the linker does not find the symbol and may lead to an “unresolved external symbol” or “undefined reference”. You can also check another post about how to fix no valid ip configuration ethernet.

The way to repair this error is to explicitly scope the variable utilizing ‘::’ outside the primary prior to using it.

# 2) When we have externals variables referenced in the source file, and we have actually not linked the files that specify these external variables.

This case is demonstrated listed below:.

#include

#include

using namespace sexually transmitted disease;.

extern int i;.

extern void g();.

void f()

i++;.

g();.

int main()

Output:

In general, in the case of an “unresolved external symbol”, the put together code for any things like function fails to find a sign to which it makes a recommendation, possibly since that sign is not specified in the object files or any of the libraries specified to the linker.

Conclusion.

In this tutorial, we discussed some major mistakes in C++ that are critical and can impact the program circulation and might even result in an application crash. We checked out everything about Segmentation fault, Unresolved external symbol, and Undefined reference in detail.

Although these mistakes can take place anytime, from the causes that we discussed, we understand that we can quickly avoid them by thoroughly establishing our program.

Introduction

In this article I’ll be looking at the “undefined reference” error message (or “unresolved external symbol, for Visual C++ users). This is not actually a message from the compiler, but is emitted by the linker, so the first thing to do is to understand what the linker is, and what it does.

Linker 101

To understand the linker, you have to understand how C++ programs are built. For all but the very simplest programs, the program is composed of multiple C++ source files (also known as “translation units”). These are compiled separately, using the C++ compiler, to produce object code files (files with a .o or a .obj extension) which contain machine code. Each object code file knows nothing about the others, so if you call a function from one object file that exists in another, the compiler cannot provide the address of the called function.

This is where the the linker comes in. Once all the object files have been produced, the linker looks at them and works out what the final addresses of functions in the executable will be. It then patches up the addresses the compiler could not provide. It does the same for any libraries (.a and .lib files) you may be using. And finally it writes the executable file out to disk.

The linker is normally a separate program from the compiler (for example, the GCC linker is called ld) but will normally be called for you when you use your compiler suite’s driver program (so the GCC driver g++ will call ld for you).

Traditionally, linker technology has lagged behind compilers, mostly because it’s generally more fun to build a compiler than to build a linker. And linkers do not necessarily have access to the source code for the object files they are linking. Put together, you get a situation where linker errors, and the reasons for them, can be cryptic in the extreme.

Undefined reference

Put simply, the “undefined reference”  error means you have a reference (nothing to do with the C++ reference type) to a name (function, variable, constant etc.) in your program that the linker cannot find a definition for when it looks through all the object files and libraries that make up your project. There are any number of reasons why it can’t find the definition – we’ll look at the commonest ones now.

No Definition

Probably the most common reason for unresolved reference errors is that you simply have not defined the thing you are referencing. This code illustrates the problem:

int foo();

int main() {
    foo();
}

Here, we have a declaration of the function foo(), which we call in main(),  but no definition. So we get the error (slightly edited for clarity):

a.cpp:(.text+0xc): undefined reference to `foo()'
error: ld returned 1 exit status

The way to fix it is to provide the definition:

int foo();

int main() {
    foo();
}

int foo() {
    return 42;
}

Wrong Definition

Another common error is to provide a definition that does not match up with declaration (or vice versa). For example, if the code above we had provided a definition of foo() that looked like this:

int foo(int n) {
    return n;
}

then we would still get an error from the linker because the signatures (name, plus parameter list types) of the declaration and definition don’t match, so the definition actually defines a completely different function from the one in the declaration. To avoid this problem, take some care when writing declarations and definitions, and remember that things like references, pointers and const all count towards making a function signature unique.

Didn’t Link Object File

This is another common problem. Suppose you have two C++ source files:

// f1.cpp
int foo();

int main() {
    foo();
}

and:

// f2.cpp
int foo() {
    return 42;
}

If you compile f1.cpp on its own you get this:

f1.cpp:(.text+0xc): undefined reference to `foo()'

and if you compile f2.cpp on its own, you get this even more frightening one:

crt0_c.c:(.text.startup+0x39): undefined reference to `WinMain@16

In this situation, you need to compile both the the source files on the same command line, for example, using GCC:

$ g++ f1.cpp f2.cpp -o myprog

or if you have compiled them separately down to object files:

$ g++ f1.o f2.o -o myprog

For further information on compiling and linking multiple files in C++, particularly with GCC, please see my series of three blog articles starting here.

Wrong Project Type

The linker error regarding WinMain  above can occur in a number of situations, particularly when you are using a C++ IDE such as CodeBlocks or Visual Studio. These IDEs offer you a number of project types such as “Windows Application” and “Console Application”. If you want to write a program that has a int main() function in it, always make sure that you choose “Console Application”, otherwise the IDE may configure the linker to expect to find a WinMain() function instead.

No Library

To understand this issue, remember that a header file (.h) is not a library. The linker neither knows nor cares about header files – it cares about .a and .lib files. So if you get a linker error regarding a name that is in a library you are using, it is almost certainly because you have not linked with that library. To perform the linkage, if you are using an IDE you can normally simply add the library to your project, if using the command line, once again please see my series of blog articles on the GCC command line starting here, which describes some other linker issues you may have.

Conclusion

The unresolved reference error can have many causes, far from all of which have been described here. But it’s not magic – like all errors it means that you have done something wrong, in you code and/or your project’s configuration, and you need to take some time to sit down, think logically, and figure out what.

  1. Types of Errors in C++
  2. Undefined Reference to a Class::Function() in C++
  3. Resolve Undefined Reference to a Class::Function() Due to No Function Definition in C++
  4. Resolve Undefined Reference to a Class::Function() Due to Not Linked Object Files in C++
  5. Resolve Undefined Reference to a Class::Function() Due to Not Compiled Dependent Files in C++

Undefined Reference to Class::Function() in C++

This tutorial briefly discusses one of the most common and equally critical errors in C++ programming (i.e., Undefined Reference to a Class::Function()).

First, we will briefly discuss different errors while coding in C++. Then, we will explain the causes and fixes for the undefined reference error.

Types of Errors in C++

The C++ codes may be subjected to errors or bugs for multiple reasons like any other programming language. These errors are broadly classified into the following error categories:

  • Syntax Errors are the errors that occur due to violations in the rules of C++ or any syntaxes.
  • Run-time Errors are the errors that occur when there is no programming issue syntactically but are detected at the time of execution and lead to a program crash.
  • Logical Errors occur when we are not getting our desired results or output, which means there are mistakes in the logic of our program.
  • Linker Errors are the type of errors when the program is compiled successfully and is trying to link some other objects with our main object file, and thus executable is not generated. For example, any wrong prototype of the function defined, any incorrect header file included, etc.

Undefined Reference to a Class::Function() in C++

This is the most frequently occurring error in C++ and is equally critical, especially for new programmers. This type of linker error can affect the running of the program.

These errors mainly occur when the program is compiled successfully and is at the linking phase trying to link other object files with the main object. There are some cases when the program gives some output, and this error occurs.

So, it is sometimes complicated to trace down and correct such errors.

Undefined Reference error occurs when we have used any reference to some class, function, or variable. The linker cannot find its definition in all the linked object files and libraries, thus generating the error Undefined Reference to a Class::Function().

There can be several causes of these errors, but we will discuss some of them here.

Resolve Undefined Reference to a Class::Function() Due to No Function Definition in C++

This can be the most straightforward reason for this error, that you have provided the prototype of the function but forgot to give its definition.

When you create a reference for that function, the linker will fail to find its definition, thus generating an error Undefined Reference to a Class::Function().

This is demonstrated in the example below:

#include <iostream>
class Square {
    public:
        double length;      // Length of a box
        double width;     // Breadth of a box
        double height;      // Height of a box

        double getArea(void);
};
int main()
{
        Square sq1;
        sq1.getArea();
        return 0;
}

Output:

(.text+0x15): undefined reference to Square::getArea()
collect2.exe: error: ld returned 1 exit status

Resolve Undefined Reference to a Class::Function() Due to Not Linked Object Files in C++

When using a different file to define a class, we need to include that file in the main function file to be linked with the main object file when linking the program.

In the example below, we defined the Square class separately in another file. In the main file, we are referencing its object, so it will give an undefined reference error as the file is not linked.

Example:

#include <iostream>
using namespace std;

int main()
{
    Square sq1;
    cout<<sq1.getArea();
    return 0;
}

Example (Square.cpp):

class Square {
    public:
        double length;      // Length of a box
        double width;     // Breadth of a box
        double height;      // Height of a box
        double getArea(void){
        return length*width;
    }
        void setLength(double l){
        length = l;
    }
};

The solution to this problem is to link the Square.cpp file to the main file in the following code.

#include <iostream>
#include "square.cpp"
using namespace std;

int main()
{
    Square sq1;
    cout<<sq1.getArea();
    return 0;
}

Resolve Undefined Reference to a Class::Function() Due to Not Compiled Dependent Files in C++

This type of error also occurs when all of the program’s dependencies are not compiled successfully. For a linker to generate an executable successfully, it is necessary to compile all the dependencies before initiating the linking phase.

This is inevitable so that the linker may find all the dependent object files (i.e., .o files) easily. If any dependent object files go missing, the linker will generate an undefined reference error.

Note

If you use GNU’s g++ compiler, the Bash command g++ -c abc.cpp will generate a corresponding object file abc.o without invoking the linker.

Apart from the situations discussed above, there can be many other situations for the undefined reference error. The programmer must correctly define all identifiers (e.g., functions, variables, and objects) to avoid such problems.


Error description:

  • What are undefined reference/unresolved external symbol errors? What are common causes and how to fix/prevent them?

Solution 1:

  • The specified errors occur during this last stage of compilation, most commonly referred to as linking. It basically means that we compiled a bunch of implementation files into object files or libraries and now we want to get them to work together.

Common causes include:

  • Failure to link against appropriate libraries/object files or compile implementation files
  • Declared and undefined variable or function.
  • Common issues with class-type members
  • Template implementations not visible.
  • Symbols were defined in a C program and used in C++ code.
  • Incorrectly importing/exporting methods/classes across modules/dll. (MSVS specific)
  • Circular library dependency
  • undefined reference to `[email protected]’
  • Interdependent library order
  • Multiple source files of the same name
  • Mistyping or not including the .lib extension when using the #pragma (MSVC)
  • Problems with template friends
  • Inconsistent UNICODE definitions

Solution 2:

  • It can also happen that we forget to add the file to the compilation, in which case the object file won’t be generated. In gcc we’d add the files to the command line. In MSVS adding the file to the project will make it compile it automatically (albeit files can, manually, be individually excluded from the build).

Solution 3:

  • The order in which libraries are linked DOES matter if the libraries depend on each other. In general, if library A depends on library B, then libA MUST appear before libB in the linker flags.

Solution 4:

  • The function (or variable) void foo() is defined in a C program and you attempt to use it in a C++ program:
void foo();
int main()
{
    foo();
}
click below button to copy the code. By c++ tutorial team
  • The C++ linker expects names to be mangled, so you have to declare the function as:
extern "C" void foo();
int main()
{
    foo();
}
click below button to copy the code. By c++ tutorial team
  • Equivalently, instead of being defined in a C program, the function (or variable) void foo() is defined in C++ but with C linkage:
extern "C" void foo();
click below button to copy the code. By c++ tutorial team
  • and we attempt to use it in a C++ program with C++ linkage.
  • If an entire library is included in a header file (and was compiled as C code); the include will need to be as follows;
extern "C" {
    #include "cheader.h"
}
click below button to copy the code. By c++ tutorial team

Solution 5:

  • We will be able to get rid of an unresolved external error in Visual Studio 2012 just by recompiling the offending file. When we re-build, the error goes away.
  • This usually happens when two (or more) libraries have a cyclic dependency. Library A attempts to use symbols in B.lib and library B attempts to use symbols from A.lib. Neither exist to start off with. When we attempt to compile A, the link step will fail because it can’t find B.lib. A.lib will be generated, but no dll. We then compile B, which will succeed and generate B.lib. Re-compiling A will now work because B.lib is now found.

Понравилась статья? Поделить с друзьями:
  • Undefined reference to pow collect2 error ld returned 1 exit status
  • Undefined reference to main collect2 error ld returned 1 exit status
  • Undefined reference to collect2 exe error ld returned 1 exit status
  • Undefined object 7 error index primary does not exist
  • Undefined function or variable matlab как исправить