symbol lookup error - c++

I am writing a shared library with C++ under Ubuntu. The source code contains two files: ClassA.h and ClassA.cpp. Bellow are parts of the contents:
ClassA.h:
namespace calss_a{
class ClassA{
public:
...
void foo(int nBlockIndex);
...
}
}
ClassA.h:
namespace calss_a{
...
void classA::foo(int nBlockIndex){printf("....");}
...
}
The compiled .so file from the above source codes is used in test.cpp as follows:
...
class_a::ClassA * ptr = new class_a::ClassA();
...
ptr->foo(0);
...
However, when the executable build from test.cpp runs, there is an error as follows:
symbol lookup error: /home/hzhu/test: undefined symbol: _ZN16class_a15ClassA16fooEj
But if I change in ClassA.cpp and ClassA.h the type of foo()'s argument "nBlockIndex" from "int" to "unsigned in", and recompile the .so file, then the problem disappears. In a further experiment, the argument "nBlockIndex"'s type is still defined to be "int", but in test.cpp I call "foo" this way:
ptr->foo(1); //pass 1 instead of 0
then the problem disappear as well.
Can anyone tell me what is going on here?
Thanks.

I am a bit new to this kind of thing myself, but I am also running into a symbol lookup error and so thought I would share what I have found out.
The problem with symbol lookup errors usually is that something is being defined two different ways in two different places. If you do
nm -u your-executable | grep undefined-symbol
then you will find out where the symbols being used in an object file or executable file are defined

Related

g++ fails to link .o files into an executable

I am doing an example drill in the textbook I am using to learn from. All I need to do is compile, link and run the following 3 files:
//file my.h
extern int foo;
void print_foo();
void print(int);
my.h is a simple header file that declares the two functions and a 'global' int foo, with no initial value.
//file my.cpp
#include "my.h"
#include "std_lib_facilities.h" //not included but not source of error
void print_foo()
{
cout << foo << endl;
}
void print(int i)
{
cout << i << endl;
}
my.cpp contains the implementation of the functions included from my.h. std_lib_facilities.h is a file from the textbook, and is not the source of error (according to g++). I can edit it into the body of the question if needed.
//file use.cpp
#include "my.h"
#include <iostream>
int main() {
foo = 7;
print_foo();
print(99)
char cc; cin >> cc;
return 0;
}
use.cpp serves as the main implementation file in this program, and tries to use all three declared & defined objects.
I took the two step command approach to build using g++. First, I compiled both .cpp files:
g++ -c my.cpp use.cpp
which created two object files, my.o and use.o. I used the following command to link them:
g++ -o myprog my.o use.o
giving me this error:
Undefined symbols for architecture x86_64:
"_foo", referenced from:
print_foo() in my.o
_main in use.o
(maybe you meant: __Z9print_foov)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
I have tried putting
int foo;
into my.h instead of
extern int foo;
which gave me the same error.
I have tried using the
-std=c++11
flag as well which resulted in the same error.
I am using a MacBook Pro with the latest macOS (just updated in fact), if that helps with interpreting the error message.
I have tried to initialize foo, which didn't change anything.
In addition, I have tried updating the command line tools, same error.
From what I understand, the error is telling me that, even though my.h is included in both files, neither one can actually implement any function using the foo variable (which it calls _foo), despite it being explicitly declared in my.h. My guess is that the linker is using the wrong names under the hood, which make it impossible to link into an executable. This comes from the fact that the error mentioned a
__Z9print_foov
which exists nowhere in any of the files.
It almost seems like a g++ or macOS/Command Line Tools bug at this point. I don't want to add the declarations each time, because that creates duplicate symbol errors anyway. Putting my.cpp and use.cpp into one file would probably link properly, but I need to make sure that I can actually link multiple cpp files, because I will eventually (hopefully) be working with multiple cpp files that need to be linked. Any help is appreciated!
Here you declare a variable:
extern int foo;
and you use the variable:
cout << foo << endl;
but you did not define the variable anywhere. The linker error says that the linker could not find the variable's definition. To fix this, put int foo; at file scope in one of the .cpp files.
In the question you say that changing extern int foo; to int foo; gives the same error. However if you look more carefully at the error message I think you will find that it gives a different one, about multiple definitions.
I suggest to compile in two commands g++ -Wall -c my.cpp (that gives a my.o) and g++ -Wall -c use.cpp (giving use.o), then link a program with g++ my.o use.o -o myprog. Actually you should write a Makefile (see this for inspiration) and simply run make
Your translation units my.cpp and use.cpp are both declaring some extern int foo; variable which is never defined. So you need to define it in one single file (but not in others!), probably by adding (into my.cpp alone for example)
int foo;
(without the extern) or even with some explicit initial value e.g. int foo = 34;
This comes from the fact that the error mentioned a __Z9print_foov which exists nowhere
It is a mangled name, which is referenced (but not defined) in both object files (see also this).
It almost seems like a g++ or macOS/Command Line Tools bug at this point
You are very unlikely to find bugs in compiler tools (both GCC & Clang/LLVM are extremely well tested; since they are multi-million lines free software, they do have residual bugs, but you have more chances to win at the lottery than to be affected by a compiler bug). I'm coding since 1974, and it happened to me only once in my lifetime. A more realistic attitude is to be more humble, and question your own code (and knowledge) before suspecting the compiler or build chain.
BTW, always compile first with all warnings and debug info (e.g. g++ -Wall -g and perhaps also -Wextra). Use the gdb debugger. When you are convinced that your code has no bugs, you might benchmark it by asking the compiler to optimize (so use g++ -Wall -O2 perhaps also with -g to compile).
Read also the linker wikipage. Dive into your C++ textbook (see also this site and the C++11 standard, e.g. n3337 draft) to understand the difference between declaring and defining some variable or function. You generally declare a global extern variable in some common header (included in several translation units), and define it once somewhere else, but the good practice is to avoid having lots of global variables. See also C++17 new inline variables.

Undefined reference error when using a simple class inside my function

I am getting nuts with this error so I thought some of more experienced developers can help me in this regard.
I am trying to compile a sample project which uses a C++ library (named Poco). My project is linked to compiled poco libraries.
Below is my (most simplified) code:
#include "Poco/UUID.h"
class x
{
void func1()
{
new Poco::UUID(); //A
}
};
void func1()
{
new Poco::UUID(); //B
}
Now when above code is compiled, line 'A' has no error but for line 'B' linker says:
undefined reference to `Poco::UUID::UUID()'
What is the reason? When I instantiate a class from external lib in a class method no error occurs but the same code in a function produces linker error? (When I comment line B, no error occurs and linker output files are generated)
My configuration: Win7/g++/CodeLite/MinGW-4.7.1
*Update 2:*Thanks. My problem is now resolved and the issue is that I had compiled library using MSVC compiler while my application was being compiled using g++ (both under Windows platform). So I re-compiled library using g++ and everything works fine now.
Update 1: here is my IDE's output when I build my project:
C:\Windows\system32\cmd.exe /c "mingw32-make.exe -j 4 -e -f "dll1.mk" all"
----------Building project:[ dll1 - Debug ]----------
g++ -shared -fPIC -o ./Debug/dll1.so #"dll1.txt" -L. -Lc:/poco/lib -lPocoFoundationd
./Debug/PluginLibrary.o: In function `Z5func1v':
C:/Users/PARS/Documents/codelite/workspace1/dll1/PluginLibrary.cpp:12: undefined reference to `Poco::UUID::UUID()'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe: *** [Debug/dll1.so] Error 1
dll1.mk:77: recipe for target `Debug/dll1.so' failed
1 errors, 0 warnings
Your member function x::func1() is never ODR-used in that compilation unit (source file). Most compilers only generate compiled code for a member function defined inside the class definition if that member function is ODR-used within the compilation unit that is being compiled. Suppose some other source file does use x::func1(). If you compile that other source file, the compiler will produce object code for x::func1() in the object file that corresponds to that other source file.
The compiler can get away with bypassing the process of generating compiled code for x::func1() here because the class definition has to be the same across all compilation units. If you compile some other source file that has a different definition of class x you have violated the one definition rule. This is undefined behavior and no diagnosis is required.
If no source file uses x::func1() you have some dead code that just never happens to be compiled. The code has an error but it's never detected.
The compiler cannot get away with bypassing generating compiled code for the free function func1(). This function has external linkage; there's no way the compiler can tell if it might be used somewhere else. The compiler must generate compiled code for that free function.
Here's a minimum working example:
class Missing {
public:
Missing();
int value;
};
class UsesMissing {
public:
int use_missing () {
Missing missing;
return missing.value;
}
int dont_use_missing () {
return 0;
}
};
#ifdef DEFINE_USE_MISSING
int use_missing () {
Missing missing;
return missing.value;
}
#endif
int main () {
UsesMissing test;
#ifdef USE_MISSING
return test.use_missing();
#else
return test.dont_use_missing();
#endif
}
Compile with neither DEFINE_USE_MISSING or USE_MISSING defined and this compiles and links just fine with g++ and clang++. Define either one of those flags and the file fails in the link step because of the undefined reference Missing::Missing().
You should link with the correct library to fix your link (see Poco docu for the correct one).
func1 has extern linkage and so linker need Poco::UUID
whereas X::func1 is inline/private/unused.
if you use static foo1() or inline foo1() the linker error disappears
if you use x::func1 or implement x::func1 outside of the class x{}; the error linker appears

Persistent undefined reference

I am having a persistent undefined symbol error in Eclipse on MAC OS X. I can't figure
out the source of the error.
The error occurs according to the compiler when I try to use GA_Operations and gaAlgorithm->run_algorithm..... below:
int Application::execute_Algorithm()
{
if (this->GA_On)
{
GA_Operations *gaAlgorithm = new GA_Operations();
gaAlgorithm->run_algorithm(blocksSequence, bins);
}
else
{
packingAlgorithm->run_algorithm(blocksSequence, bins); return 0;
} //
return 0;
}
The error showing is:
Undefined symbols for architecture x86_64:
"binproject::GA_Operations::run_algorithm(binproject::Blocks_Sequence&, binproject::BinContainer&)", referenced from:
binproject::Application::execute_Algorithm() in Application.o
"binproject::GA_Operations::GA_Operations()", referenced from:
binproject::Application::execute_Algorithm() in Application.o
And the declaration is:
class GA_Operations {
public:
GA_Operations();
~GA_Operations();
//call from main application to execute algorithm
void run_algorithm(Blocks_Sequence &b_seq, BinContainer &container);
...
};
It also throws a similar error anytime I try to define a declared function in the
implementation (CPP) file.
Any ideas? This only seems to happen with this class.
Also, I apologize if there is a problem with the code indenting, I'm
The error you are showing is a linker error. This means that the compiler thinks something exists, but the linker can't find where you've defined (not declared) it. Somewhere you need something like this:
GA_Operations::GA_Operations()
{
// construct
}
void GA_Operations::run_algorithm(Blocks_Sequence &b_seq, BinContainer &container)
{
// stuff
}
Do you have that anywhere? If so, is it in the same file that Application::execute_Algorithm is in?
If it isn't, where is it? How are you compiling your whole program together so the stuff in these different files ends up in the same executable?
I'm not at all sure how to make Eclipse do what you need. I know it's possible, but I'm for familiar with pure command-line tools. You need to tell Eclipse that the .cpp file that contains the above definitions is part of your project and should be compiled and linked into the executable you're created.
Turns out this was an issue with linker settings. I turned on generating makefiles automatically and the problem resolved itself.

Linking with a library from external directory

Edit: I have updated my question with changes I've made, upon answers.
I'm trying to link to a little library that I've wrote to learn ho this is done with C++ with no luck. G++ is complaining with undefined reference.
The root directory of library I want to link is in directory ~/code/gklib/cxx/. The structure of this directory is as follows:
~/code/gklib/cxx/
|
|`-> gk.{hh,cc}
|`-> libgk.o
|
`-> lib/
|
`-> libgk.a
I have compiled gk.cc with -c flag, then transformed the resulting object file to a .a file with ar rvsc lib/libgk.a libgk.o.
The client to this library is at folder ~/code/cpp. In this directory I compiled some_stuff.cc to an object file again, then I tried to link to it with this command:
$ cxx some_stuff.o -L../gklib/cxx/lib -lgk -o some_stuff
I get this error:
some_stuff.o: In function `main':
some_stuff.cc:(.text+0x49): undefined reference to `void GK::algorithms::insertionSort<int, 5ul>(int*)'
collect2: error: ld returned 1 exit status
These are contents of these files:
~/code/cpp/some_stuff.cc
#include <cstdlib>
#include <iostream>
#include <gk.hh>
using namespace std;
int main(int argc, char **argv) {
int i = -1;
int arr[5] = { 3, 4, 2, 1, 5 };
const size_t len = sizeof(arr)/sizeof(int);
GK::algorithms::insertionSort<int, len>(arr);
while(++i < 5)
cout << arr[i] << " ";
cout << endl;
exit(EXIT_SUCCESS);
}
~/code/gklib/cxx/gk.cc
#include "gk.hh"
template<class T, size_t len>
void GK::algorithms::insertionSort(T arr[len]){
// insertion sort
}
~/code/gklib/cxx/gk.hh
#pragma once
#include <cstdlib>
#define NAMESPACE(ns) namespace ns {
#define END_NAMESPACE(ns) }
NAMESPACE(GK)
NAMESPACE(algorithms)
template<class T, size_t len>
extern void insertionSort(T arr[len]);
END_NAMESPACE(algorithms)
END_NAMESPACE(GK)
I've tried many variations on my commands with no result. Internet is full of tutorials and forums with instructions those did not work for me. This code ran perfectly when all the stuff was in one file. How can I resolve this problem? Thanks in advance.
I think it's more something like:
cxx some_stuff.o -L$HOME/gklib/cxx/lib -B../gklib/cxx/lib -lgklib -o some_stuff
-lgklib, not -Igklib (-I option specify an include folder)
but you'll have to rename your gklib.a by libgklib.a
Maybe you can even remove -B../gklib/cxx/lib, just try it out :)
I see several problems: in order:
If this is your exact command line, the -L option doesn't
point to the structure you've shown above (where there is no
cxx in the path).
I don't know why you're using -B. This tells the compiler
where to look for its libraries, etc. Normally, this is only
necessary when you want to test parts of the compiler you've
modified.
I don't see where you've specified to link against the
library. Since the library doesn't respect the usual naming
conventions (libname.a), you'll have to
specify it directly (in the same way you'd specify an object
file), and the -L option isn't used. Alternatively, you name
it libgk.a, or something like that, and add a -lgk to the
command line, after your object files.
Finally, the error messages refer to an instantiation of
a template. This typically occurs because the implementation of
the template is in a source file, not in the header. The
standard requires that the implementation be visible when it
triggers the instantiation of a template. The way g++ (and
almost every other compiler) works is that if the implementation
isn't visible, they suppose that the template will be
instantiated in another translation unit, and output external
references to it. But if the implementation is in a source,
there will be no instantiation, and you'll get a linker error.
(You'll also not find the assembler for the instantiation
anywhere, either, because the template hasn't been
instantiated.) You should include the source code at the bottom
of your header, and not compile it separately.
I have solved this problem, with the help of this and this questions. The problem lies in the fact that void insertionSort(T *) is a template function, and template functions can only be implemented in header files. The reason for this is, the compiler needs to reach the definition of the to create a new function for each call to it with a different type as the argument to template. I have moved the definition of this function to gk.h, which resulted in a successfull compilation and linkage.

Can I link unresolved reference to abort?

I'm trying to write some small tests for a fairly small part of a fairly large project. Attempting to link this beast is unfortunately fairly impossible without linking the entire project together, which I don't want to do (it's a pretty complex system for finding all the dependencies and stuff, and I perfer not to meddle with it).
Now, I know for certain that the functions that the referenced functions won't be called during my test, the just happen to be part of functions which share file with stuff that I do test.
Is there any way to simply link these unresolved references to, let's say, abort, or something? Or is there a tool which creates the appropriate stub object file where all calls result in abort, given the set of object files that I have?
I use gcc (g++) for compiling/linking, version 3.4.4. Platform is unix (solaris/sparc if that's important).
You can just tell linker to ignore unresolved symbols. I couldn't find option that links them to abort or something like that.
The policy to ignore unresolved symbols in object files only is the most natural, I suppose:
gcc -Wl,--unresolved-symbols=ignore-in-object-files obj.o another.o etc.o
Other options include (quoting man ld):
--unresolved-symbols=method
Determine how to handle unresolved symbols. There are four possi-
ble values for method:
ignore-all
Do not report any unresolved symbols.
report-all
Report all unresolved symbols. This is the default.
ignore-in-object-files
Report unresolved symbols that are contained in shared
libraries, but ignore them if they come from regular object
files.
ignore-in-shared-libs
Report unresolved symbols that come from regular object files,
but ignore them if they come from shared libraries. This can
be useful when creating a dynamic binary and it is known that
all the shared libraries that it should be referencing are
included on the linker's command line.
The behaviour for shared libraries on their own can also be con-
trolled by the --[no-]allow-shlib-undefined option.
Normally the linker will generate an error message for each
reported unresolved symbol but the option --warn-unresolved-sym-
bols can change this to a warning.
On my Linux system attempts to call the unresolved function result in "Segmentation fault".
Trying to compile the following program
#include <iostream>
extern int bar();
int foo()
{
return bar() + 3;
}
int main()
{
std::cout << "Hello, world!" << std::endl;
// std::cout << foo() << std::endl;
return 0;
}
results in
$ g++ -o main main.cc
/tmp/ccyvuYPK.o: In function `foo()':
main.cc:(.text+0x5): undefined reference to `bar()'
collect2: ld returned 1 exit status
But we can tell the linker to ignore unresolved symbols and run it just fine:
$ g++ -Wl,--unresolved-symbols=ignore-all -o main main.cc
$ ./main
Hello, world!
Say some unresolved function is called by your test harness (simulate this by uncommenting the call to foo), it will compile and link fine, but you'll get a segfault when you execute the program. Be sure to ulimit -c unlimited so you get a core.
Well one way I can think of is to first compile the .o files for you library.
Then use a tool like nm (common on *nix systems) to get all of the symbols, in nm, all "external" (aka ones which are not found in this .o) are of type U (it may be different for non-GNU versions of nm see your documentation).
If your library is all one source file, then it is simple, pretty much all symbols of type U will be either a function found in another library or will be unresolved at link time. It is slightly more complicated if your library is going to be more than one source file since you will have inter-source file dependencies.
So now you have a a means to create a potential list of unresolved externals, then you can create a "test_stub.c" which has a stub symbols for each one, which you could fill with something like this:
void some_func() { abort(); }
where some_func is a would be unresolved external. Compile and link this with your library and all calls should result in an abort.
Try GCC alias attribute:
/* cannot directly alias to yet undefined symbols,
* so need an intermediate function.
*/
static void do_abort() { abort(); }
void func0() __attribute__ ((weak, alias ("do_abort")));
void func1() __attribute__ ((weak, alias ("do_abort")));
...