views:

132

answers:

4

Hi, I have 3 tiny files which I use to make a static library and an app:

test.h

#ifndef TEST_H
#define TEST_H

class Test
{
    public:
        Test();
};

extern Test* gpTest;

#endif

test.cpp

#include "test.h"

Test::Test()
{
    gpTest = this;
}   

Test test;

main.cpp

#include "test.h"
#include <iostream>

using namespace std;

Test* gpTest = NULL;

int main()
{
    return 0;
}

BUILD

g++ -c test.cpp -o test.o
ar cr test.a test.o
g++ -c main.cpp -o main.o
g++ main.o -o app -Wl,--whole-archive -L/home/dumindara/intest/test.a -Wl,-no--whole-archive

ERROR (linking step)

/usr/lib64/gcc/x86_64-suse-linux/4.3/../../../../x86_64-suse-linux/bin/ld: cannot find -lgcc_s
collect2: ld returned 1 exit status

I tried everything : using -static-libgcc and linking to static libstdc++ :(. Can't get this to work. It is all due to --whole-archive flag. But I can't do without it. Please help. Thanks.

+5  A: 

I think -- is the problem here:

-Wl,-no--whole-archive

Try with

-Wl,-no-whole-archive

edit

About not seeing the test symbol in your app with nm app: I think you don't need -L since you give full path and name of test.a - do either

-Wl,--whole-archive -L/home/dumindara/intest/ -ltest -Wl,-no-whole-archive

or

-Wl,--whole-archive /home/dumindara/intest/test.a -Wl,-no-whole-archive
Dmitry Yudakov
Yes, it links ok now. But I still can't see the `test` symbol in my app with `nm app`. What to do?
nakiya
@nakiya see my edit
Dmitry Yudakov
Thanks Dmitry, you saved my life!!! The lib was actually not getting liked I think. Now it works fine. :D
nakiya
+6  A: 

You have a typo. -no--whole-archive should be --no-whole-archive. Fixing the typo fixes the linker error.

Arrrgh!!! Foolish me...
nakiya
+4  A: 

With regards to the comments so far: just drop the -Wl option entirely. Let g++ do its thing.

As for not finding the symbol test with nm, why would you expect anything else? You don't use it, your program doesn't need it, so it isn't pulled in. (If for some reason you need to include an object file which isn't referenced, e.g. because static initializers will make it visible, then specify the object file---don't put it in a library, which is the standard way of saying don't include it unless needed.)

-- James Kanze

James Kanze
I will be actually using `gpTest`. Not in that form : it will be a vector holding all the version information about my static libraries linked to the program. So if linker throws away `test` it is a problem. I thought that is exactly what `--whole-archive` solves. Am I wrong?
nakiya
A: 

whole-archive works, you are just not linking the lib. The correct thing to do is :

ar cr libtest.a test.o

and link with

-Wl,--whole-archive -L/home/dumindara/intest/ -ltest
shodanex
yep. Dmitry Yudakov and you sir are right!
nakiya