C++ strange compile linker error - c++

I am trying to compile large C++ project and I am getting this strange error. I know that it is linking error but couldn't figure out what it is exactly.
test_oqlquery.o:(.rodata._ZTV8r_MarrayIhE[vtable for r_Marray]+0x8): undefined reference to r_Marray<unsigned char>::~r_Marray()'
test_oqlquery.o:(.rodata._ZTV8r_MarrayIhE[vtable for r_Marray<unsigned char>]+0xc): undefined reference tor_Marray::~r_Marray()'
test_oqlquery.o:(.rodata._ZTV8r_MarrayIhE[vtable for r_Marray]+0x28): undefined reference to `r_Marray::print_status(std::basic_ostream >&) const'
What does this error mean ? And, is it possible to see the line number where there error is happening ? How ? I am mainly concerned with what this means ".rodata._ZTV8r_MarrayIhE[vtable for r_Marray]+0x28"
Actually, my error is like this, but dont know why everything inside angle bracket are missing, so replacing them with " ", here is detailed error, it has something to do with template instantiation, as well
test_oqlquery.o:(.rodata._ZTV8r_MarrayIhE[vtable for r_Marray"unsigned char"]+0x8): undefined reference to `r_Marray"unsigned char"::~r_Marray()'
I am using g++ 4.3.3.
Please excuse me, I cannot submit the whole source code here as it is very large and spans over multiple directories.
Thanks a lot.

First, linker errors and compiler errors are different things. Since linker deals with object files rather than source files, compiler errors have a line number but linker errors don't.
Second, it seems that you have declared the destructor for r_Marray but have not implemented it anywhere included in the build. The same thing goes for print_status.

Either you have not defined r_Marray::~r_Marray() and r_Marray::print_status or the cpp file containing these methods were not part of your build process.
If you do have the cpp file with these methods defined, please post your Makefile.
Based on your comment to your question I am assuming that r_Marray is templated class? Do you have the definitions for the r_Marray methods in your header file?

This typically happens if you have declared a method but haven't provided or haven't linked its implementation.
For example you have
class r_Marray {
public:
~r_Marray();
};
and you intended to provide the implementation of r_Marray::~r_Marray() in file r_Marray.cpp but forgot to do it - it will compile fine but not link with the error you see. Or you could have provided the implementation but not include the file with that implementation into the input of the linker.

Related

How do I rectify inconsistent Unresolved External errors? [duplicate]

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 9 years ago.
I'm trying to wrap my head around C++ developement using the SFML library. I'm following a tutorial (http://www.gamefromscratch.com/page/Game-From-Scratch-CPP-Edition-Part-7.aspx), and using visual studio 2010.
A problem I keep running into regards unresolved externals. I'm really struggling with this, because unlike most errors I run into, it doesn't seem to a) have anything to do with the code, and b) doesn't behave consistently. Rather than give y'all a specific example and ask for help solving that one example, I'm hoping to develop a more reliable way of attacking these problems. I'll give you an outline of a common occurance though.
I have a solution with 8 header files and 8 cpp files that correspond to them. The solution is stable: It compiles and runs with no errors or warnings.
I'll go into a header file and add this line:
virtual void DoNothing();
I'll then go into the matching cpp file and write the method:
void DoNothing(){};
I compile and run, and get 5 unresolved external errors. They don't point to any line of code, so I don't really know how to fix them, but I obviously did something wrong. Fair enough. Trying to get back to a stable state, I delete the two lines of code I had inserted, and compile. Even though the code is identical to the last stable state, I get the same unresolved external errors.
Trying random things, I go into another cpp file and reverse the order of two included header files. The game compiles now. If I switch the order of the included header files back, it compiles.
What the hell are unresolved external errors? Why don't they seem to behave consistently with the code I've entered? How do I read them to find out what the problem is, and how do I avoid them in the first place?
Thank you.
ps: If there are more specific details I should provide, please just let me know.
"Unresolved External" errors mean that your code is referring to something (usually a function or method, but can be a variable too) that does not exist. These are link errors, and not compile errors; that's why you don't get a line number and more helpful error messages.
Let me give you a little background on how C++ code is turned into an executable (and keep in mind that I'm simplifying things a bit.)
Each C++ source file (and not header file) in your project is compiled separately. A ".cpp" file and all the headers it includes are compiled into what is called an object file or object code. (These files have a ".obj" or ".o" extension.) You can also think of library files (that is ".lib" files on Windows and ".a" files on Linux) as a collection of these object files, stored for later use.
To produce the executable programs (e.g. the EXE or DLL file on Windows) all these object files are linked together are voila!
Now, the important thing here is that each source file is compiled in isolation and independent from other source files. So, if the code in one file calls a function that is implemented in another file, the compiler won't see the actual body of that function and can only assume that as long as the declaration of the called function is visible (i.e. the prototype, i.e. the line you write in headers,) then these files are going to be linked together eventually and will leave the task of actually making the call to the linker. This usually means that as long as you include the right headers, your compiler is going to be happy.
But the linker is going to be more tenacious and pedantic. At link time, you really really need to provide the body (i.e. the implementation) of all the functions that you use all over the project. It is your task to make sure that all the right object files and libraries are linked together and the implementation of each used function exists somewhere among them exactly once (no more, no less.)
This brings us to your problem. When you get an "unresolved external" linker error, this means that the body of a function you've called does not exist anywhere in object files and libraries that you are linking together.
Obviously, one of two things is happening. Either you have included the header for an external library, but have forgotten to link in the library file itself (which is not your problem here) or you've declared (i.e. written the prototype for) a function but have forgotten to implement its body.
Keep in mind that the linker is really strict here. If you declare something like this in your class:
class Foo {
void bar (int x);
};
and then in your ".cpp" file, implement this function:
void bar (int x)
{
// Do nothing
}
then you'll get an unresolved external error if you actually call Foo::bar() anywhere in your program, because the implemented bar() is not a method of Foo (you should have implemented void Foo::bar (int x) {}.) Similar things happen if you slightly misspell or get the type of the arguments wrong or whatnot.
Reading linker errors and making sense from them can be hard. Sometimes, the name that the linker is complaining about (the "symbol" it says it can't find) is all mangled beyond recognition. This has to do with *Application Binary Interface*s (ABI) and several decades of history and precedence. Anyways, most of the time, if you look closely and the link error message, you can see what the function name was and check your code (or libraries) and try again.
Also, though it's rare, it sometimes happens that in order to solve some link issues, you have to resort to completely rebuilding your project.
Every time I've seen behavior like this it has been because of a circular reference between projects. For example, project A has a reference to an object/symbol implemented in project B while at the same time project B has a reference to an object/symbol from project A. Every time you build your solution, the tools have to compile one project first, then the other. If you make a change to the second project to be compiled, the first one cannot see the change on the first round of compilations and the build fails. If you manage to manually build project B (against a now obsolete copy of library B), then the solution starts to build correctly. More complex cycles are possible (e.g. A depends on B, which depends on C, which depends on A). You don't mention multiple projects explicitly, but I bet you have them.
These circular references are common on large solutions that have been around for a long time and have grown slowly over time. People get in habit of adding links from everything to everything because they need one function from here, a struct from there...
Hunt down these dependencies. You should be able to do a full clean rebuild from nothing but the source code. Your dependency tree should look like... Well, a tree; not a graph.

C++: Compiler and Linker functionality

I want to understand exactly which part of a program compiler looks at and which the linker looks at. So I wrote the following code:
#include <iostream>
using namespace std;
#include <string>
class Test {
private:
int i;
public:
Test(int val) {i=val ;}
void DefinedCorrectFunction(int val);
void DefinedIncorrectFunction(int val);
void NonDefinedFunction(int val);
template <class paramType>
void FunctionTemplate (paramType val) { i = val }
};
void Test::DefinedCorrectFunction(int val)
{
i = val;
}
void Test::DefinedIncorrectFunction(int val)
{
i = val
}
void main()
{
Test testObject(1);
//testObject.NonDefinedFunction(2);
//testObject.FunctionTemplate<int>(2);
}
I have three functions:
DefinedCorrectFunction - This is a normal function declared and defined correctly.
DefinedIncorrectFunction - This function is declared correctly but the implementation is wrong (missing ;)
NonDefinedFunction - Only declaration. No definition.
FunctionTemplate - A function template.
Now if I compile this code I get a compiler error for the missing ';'in DefinedIncorrectFunction.
Suppose I fix this and then comment out testObject.NonDefinedFunction(2). Now I get a linker error.
Now comment out testObject.FunctionTemplate(2). Now I get a compiler error for the missing ';'.
For function templates I understand that they are not touched by the compiler unless they are invoked in the code. So the missing ';' is not complained by the compiler until I called testObject.FunctionTemplate(2).
For the testObject.NonDefinedFunction(2), the compiler did not complain but the linker did. For my understanding, all compiler cared was to know that is a NonDefinedFunction function declared. It didn't care for the implementation. Then linker complained because it could not find the implementation. So far so good.
Where I get confused is when compiler complained about DefinedIncorrectFunction. It didn't look for implementation of NonDefinedFunction but it went through the DefinedIncorrectFunction.
So I'm little unclear as to what the compiler does exactly and what the linker does. My understanding is linker links components with their calls. So for when NonDefinedFunction is called it looked for the compiled implementation of NonDefinedFunction and complained. But compiler didn't care about the implementation of NonDefinedFunction but it did for DefinedIncorrectFunction.
I'd really appreciate if someone can explain this or provide some reference.
Thank you.
The function of the compiler is to compile the code that you have written and convert it into object files. So if you have missed a ; or used an undefined variable, the compiler will complain because these are syntax errors.
If the compilation proceeds without any hitch, the object files are produced. The object files have a complex structure but basically contain five things
Headers - The information about the file
Object Code - Code in machine language (This code cannot run by itself in most cases)
Relocation Information - What portions of code will need to have addresses changed when the actual execution occurs
Symbol Table - Symbols referenced by the code. They may be defined in this code, imported from other modules or defined by linker
Debugging Info - Used by debuggers
The compiler compiles the code and fills the symbol table with every symbol it encounters. Symbols refers to both variables and functions. The answer to This question explains the symbol table.
This contains a collection of executable code and data that the linker can process into a working application or shared library. The object file has a data structure called a symbol table in it that maps the different items in the object file to names that the linker can understand.
The point to note
If you call a function from your code, the compiler doesn't put the
final address of the routine in the object file. Instead, it puts a
placeholder value into the code and adds a note that tells the linker
to look up the reference in the various symbol tables from all the
object files it's processing and stick the final location there.
The generated object files are processed by the linker that will fill out the blanks in symbol tables, link one module to the other and finally give the executable code which can be loaded by the loader.
So in your specific case -
DefinedIncorrectFunction() - The compiler gets the definition of the function and begins compiling it to make the object code and insert appropriate reference into Symbol Table. Compilation fails due to syntax error, so Compiler aborts with an error.
NonDefinedFunction() - The compiler gets the declaration but no definition so it adds an entry to symbol table and flags the linker to add appropriate values (Since linker will process a bunch of object files, it is possible this definitionis present in some other object file). In your case you do not specify any other file, so the linker aborts with an undefined reference to NonDefinedFunction error because it can't find the reference to the concerned symbol table entry.
To understand it further lets say your code is structured as following
File- try.h
#include<string>
#include<iostream>
class Test {
private:
int i;
public:
Test(int val) {i=val ;}
void DefinedCorrectFunction(int val);
void DefinedIncorrectFunction(int val);
void NonDefinedFunction(int val);
template <class paramType>
void FunctionTemplate (paramType val) { i = val; }
};
File try.cpp
#include "try.h"
void Test::DefinedCorrectFunction(int val)
{
i = val;
}
void Test::DefinedIncorrectFunction(int val)
{
i = val;
}
int main()
{
Test testObject(1);
testObject.NonDefinedFunction(2);
//testObject.FunctionTemplate<int>(2);
return 0;
}
Let us first only copile and assemble the code but not link it
$g++ -c try.cpp -o try.o
$
This step proceeds without any problem. So you have the object code in try.o. Let's try and link it up
$g++ try.o
try.o: In function `main':
try.cpp:(.text+0x52): undefined reference to `Test::NonDefinedFunction(int)'
collect2: ld returned 1 exit status
You forgot to define Test::NonDefinedFunction. Let's define it in a separate file.
File- try1.cpp
#include "try.h"
void Test::NonDefinedFunction(int val)
{
i = val;
}
Let us compile it into object code
$ g++ -c try1.cpp -o try1.o
$
Again it is successful. Let us try to link only this file
$ g++ try1.o
/usr/lib/gcc/x86_64-redhat-linux/4.4.5/../../../../lib64/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: ld returned 1 exit status
No main so won';t link!!
Now you have two separate object codes that have all the components you need. Just pass BOTH of them to linker and let it do the rest
$ g++ try.o try1.o
$
No error!! This is because the linker finds definitions of all the functions (even though it is scattered in different object files) and fills the blanks in object codes with appropriate values
I believe this is your question:
Where I get confused is when compiler complained about DefinedIncorrectFunction. It didn't look for implementation of NonDefinedFunction but it went through the DefinedIncorrectFunction.
The compiler tried to parse DefinedIncorrectFunction (because you provided a definition in this source file) and there was a syntax error (missing semicolon). On the other hand, the compiler never saw a definition for NonDefinedFunction because there simply was no code in this module. You might have provided a definition of NonDefinedFunction in another source file, but the compiler doesn't know that. The compiler only looks at one source file (and its included header files) at a time.
Say you want to eat some soup, so you go to a restaurant.
You search the menu for soup. If you don't find it in the menu, you leave the restaurant. (kind of like a compiler complaining it couldn't find the function) If you find it, what do you do?
You call the waiter to go get you some soup. However, just because it's in the menu, doesn't mean that they also have it in the kitchen. Could be an outdated menu, it could be that someone forgot to tell the chef that he's supposed to make soup. So again, you leave. (like an error from the linker that it couldn't find the symbol)
Compiler checks that the source code is language conformant and adheres to the semantics of the language. The output from compiler is object code.
Linker links the different object modules together to form a exe. The definitions of functions are located in this phase and the appropriate code to call them is added in this phase.
The compiler compiles code in the form of translation units. It will compile all the code that is included in a source .cppfile,
DefinedIncorrectFunction() is defined in your source file, So compiler checks it for language validity.
NonDefinedFunction() does have any definition in the source file so the compiler does not need to compile it, if the definition is present in some other source file, the function will be compiled as a part of that translation unit and further the linker will link to it, if at linking stage the definition is not found by the linker then it will raise a linking error.
What the compiler does, and what the linker does, depends on the
implementation: a legal implementation could just store the tokenized
source in the “compiler”, and do everything in the linker.
Modern implementations do put off more and more to the linker, for
better optimization. And many early implementations of templates didn't
even look the template code until link time, other than matching braces
enough to know where the template ended. From a user point of view,
you're more interested in whether the error “requires a
diagnostic” (which can be emitted by the compiler or the linker)
or is undefined behavior.
In the case of DefinedIncorrectFunction, you have provides source text
which the implementation is required to parse. That text contains a
error for which a diagnostic is required. In the case of
NonDefinedFunction: if the function is used, failure to provide a
definition (or providing more than one definition) in the complete
program is a violation of the one definition rule, which is undefined
behavior. No diagnostic is required (but I can't imagine an
implementation that didn't provide one for a missing definition of a
function that was used).
In practice, errors which can be easily detected simply by examining the
text input of a single translation unit are defined by the standard to
“require a diagnostic”, and will be detected by the
compiler. Errors which cannot be detected by the examination of a
single translation unit (e.g. a missing definition, which might be
present in a different translation unit) are formally undefined
behavior—in many cases, the errors can be detected by the linker,
and in such cases, implementations will in fact emit an error.
This is somewhat modified in cases like inline functions, where you're
allowed to repeat the definition in each translation unit, and extremely
modified by templates, since many errors cannot be detected until
instantiation. In the case of templates, the standard leaves
implementations a great deal of freedom: at the least, the compiler must
parse the template enough to determine where the template ends. The
standard added things like typename, however, to allow much more
parsing before instantiation. In dependent contexts, however, some
errors cannot possibly be detected before instantiation, which may take
place at compilation time or at link time—early implementations
favored link time instantiation; compile time instantiation dominates
today, and is used by VC++ and g++.
The missing semi-colon is a syntax error and therefore the code should not compile. This might happen even in a template implementation. Essentially, there is a parsing stage and whilst it is obvious to a human how to "fix and recover" a compiler doesn't have to do that. It can't just "imagine the semi-colon is there because that's what you meant" and continue.
A linker looks for function definitions to call where they are required. It isn't required here so there is no complaint. There is no error in this file as such, as even if it were required, it might not be implemented in this particular compilation unit. The linker is responsible for collecting together different compilation units, i.e. "linking" them.
Ah, but you could have NonDefinedFunction(int) in another compilation unit.
The compiler produces some output for the linker that basically says the following (among other things):
Which symbols (functions/variables/etc) are defined.
Which symbols are referenced but undefined. In this case the linker needs to resolve the references by searching through the other modules being linked. If it can't, you get a linker error.
The linker is there to link in code defined (possibly) in external modules - libraries or object files you will use together with this particular source file to generate the complete executable. So, if you have a declaration but no definition, your code will compile because the compiler knows the linker might find the missing code somewhere else and make it work. Therefore, in this case you will get an error from the linker, not the compiler.
If, on the other hand, there's a syntax error in your code, the compiler can't even compile and you will get an error at this stage. Macros and templates may behave a bit differently yet, not causing errors if they are not used (templates are about as much as macros with a somewhat nicer interface), but it also depends on the error's gravity. If you mess up so much that the compiler can't figure it out where the templated/macro code ends and regular code starts, it won't be able to compile.
With regular code, the compiler must compile even dead code (code not referenced in your source file) because someone might want to use that code from another source file, by linking your .o file to his code. Therefore non-templated/macro code must be syntactically correct even if it is not directly used in the same source file.

c++ can't compile on linux because of a line I have deleted

I'm trying to compile my code which had a faulty line. I have deleted that line but still the compilation fail because of some ghost:
/tmp/ccaWghvE.o: In function
show(lipid*)':
membrane.cpp:(.text+0xf52): multiple
definition ofshow(lipid*)'
/tmp/ccQicBxx.o:main.cpp:(.text+0x150):
first defined here collect2: ld
returned 1 exit status
How can I get rid of that?
Thanks
Solved
I have used ralu tip and created anew folder and copied everything into it.
Thanks
You defined show(lipid*) both in main.cpp and in membrane.cpp. Either you have copies of the same function in both files or you have the function defined non-inline in a header they both include.
It says 'multiple definition'. You've defined something more than once. Make sure you only define it once!
Deleting the line the error is on rarely fixes the problem. That's often just the point the compiler realised something was wrong. You need to understand the error message, and correct the whole program, not just that line.
You have a doubly defined symbol.
presumably you defined show(lipid*) in a header file and included that header file from multiple translation units. To solve this issue, declare it inline or move the definition (the actual code) to a cpp file, retaining the declaration in the header file.

vector multiple definition link errors

vector is included in only one source file. The only stl include in the header files is string. Yet I cannot get rid of multiple definition errors (example below). Any ideas?
./plugin_dfb.o:mipsel-linux-uclibc/include/c++/4.2.0/bits/stl_bvector.h:182: multiple definition of `std::operator-(std::_Bit_iterator_base const&, std::_Bit_iterator_base const&)'
./painter.o:mipsel-linux-uclibc/include/c++/4.2.0/bits/stl_bvector.h:182: first defined here
This std::operator- is an inline function with external linkage. It appears the linker doesn't support multiple definitions of such inline functions. But the "one definition rule" of C++ (ODR) clearly allows this. Typically such symbols get "weak linkage" (GNU terminology) but I think both, the object file format and the linker, need to support this.
I would try to ask a question in a group / mailing list dedicated to your platform. Something along the lines of "Does platform X support C++ with respect to linking and the C++-related one-definition rule for inline functions and templates?".
You may also want to check the GCC documentation. It's possible that they provide a command line switch as a work-around. If you don't already use g++ as front-end to the linker, you should try it. Maybe that helps, too.
have you tried using #pragma once?
I think you have included the vector in only one header file but that header file is not having the #define block, this is resulting the redefinition of the vector header file included in it.
Please enclose your include file in the template given below and try.
#if !defined(HEADER_FILE)
#define HEADER_FILE
// Your code
#endif
As the problem appears during linking it looks to be related to template instantiation. Given instantiation implementation specifics the template functions/definitions should be put in the common include files to assure they are visible everywhere and do not duplicate header includes what may be the case here.
From what you posted problem concerns the operator - that may be used by std::distance() that may be called from find() type functions. So look if you have such functions defined or called as they may work with vectors and strings and make sure they are in shared header files.

Multiple files in Dev-C++, Linker Error. Templates

I apologise for what I'm pretty sure is a fairly stupid question, but I can't get it to work!
I'm also not sure what information is too much information so I probably won't give enough info so sorry for that too - just ask.
I began writing a class within main.cpp, and it got large so I decided to shift it to a different source file. I'm not too sure on how to do this, and can't figure anything to help fix this specific problem from internet resources (hence the asking).
I started off with the class definition including all of the function definitions above the main program function. This runs fine. I then split this up into two separate pieces. The class declaration (I think that's the correct term) above the main function and the function definitions below the main function.
This also runs perfectly well. I proceeded to cut the class declaration out into a header file. This header file is of the form
#ifndef INC_MATRIX_H
#define INC_MATRIX_H
class matrix{
//ETC
};
#endif
Which I have read somewhere is useful but I'm not entirely sure why, I think it's to stop redeclaration of the functions if the header is included more than once.
So currently we have this header file included along with the other includes. Then the main function and then the function definitions beneath the main function. This also compiles and runs perfectly well.
The next step I took was to cut the function definitions into their own separate .cpp file. The only addition that was made to this .cpp file was that some extra includes had to be added to the top (specifically iostream and cstdlib). ALSO the matrix.h file was included.
In this configuration Dev-C++ brings up linker errors when I try to compile and run the code. Specifically they are of the form
[Linker Error] undefined reference to matrix <bool>::matrix(int, int)
And the code doesn't run (obviously).
how can I fix this? Thanks in advance.
Edit: It's been discovered that this is due to the fact that it's a templated class and in the scope of the matrix.cpp file the template isn't introduced to the bool type. I now want to figure out how to fix this without adding lots of lines of code to individually make each function accept each given type.
Oh, and I appreciate that I can define the functions in the header. But I thought that we weren't meant to do that? I thought the idea was that you simply include the declaration.
The error suggests that your matrix class is a templated class. Is it? Perhaps posting the code would help.
If it is a templated class then see this FAQ for a description of the general problem with separating templated classes into header/implementation, and solutions to this problem.
I think you probably didn't add matrix.cpp to your project. It has to build that to matrix.o and link it to main.o to create your .exe.