The way to resolve this error is to compile both the files simultaneously ( For example, by using g++).Īpart from the causes already discussed, “undefined reference” may also occur because of the following reasons. When we compile these files separately, the first file gives “undefined reference” for the print function, while the second file gives “undefined reference” for the main function. In the first file, we make use of the “print ()” function which is defined in the second file. When this is done, the objects are not linked properly and it results in “undefined reference”.Ĭonsider the following two C++ programs. Here, we may have more than one source files and we might compile them independently. This issue can also give rise to the “undefined reference” error. Thus to prevent such errors, we simply cross-check if the definitions and usage of all the objects are matching in our program. Now the program gives the appropriate output. In order to get rid of this error, we correct the program as follows by providing the definition of the function func1. So when we compile this program, the linker error that says “undefined reference to ‘func1()’” is issued. Here we have only specified the prototype of function and then used it in the main function. The programmer has simply forgotten to define the object.Ĭonsider the following C++ program. This is the simplest reason for causing an “undefined reference” error. There are various reasons that cause an “undefined reference” error. As clear from definition, this error occurs in the later stages of the linking process. Thus when the linker cannot find the definition of a linked object, it issues an “undefined reference” error. We will discuss the possible causes of each of these errors and along with the precautions that we can take as a programmer to prevent these errors.Īn “Undefined Reference” error occurs when we have a reference to object name (class, function, variable, etc.) in our program and the linker cannot find its definition when it tries to search for it in all the linked object files and libraries. In this tutorial, we will discuss three types of errors that are critical from any C++ programmer’s point of view.
0 Comments
Leave a Reply. |