Re: static initialization in a static library
Re: static initialization in a static library
- Subject: Re: static initialization in a static library
- From: Jean-Daniel Dupas <email@hidden>
- Date: Wed, 4 Jun 2008 10:46:06 +0200
Le 4 juin 08 à 09:58, Nathan Litke a écrit :
My library uses static initialization to populate a table with
objects that are defined in separate source files. However this
initialization never occurs in the executable because the files are
stripped at link-time. I've searched the web, mailing lists and man
pages for help but without any luck. Here's a simple example to
illustrate my problem:
// table.cpp:
#include <vector>
std::vector<const char*>* table;
std::vector<const char*>* getTable() {
static bool init = false;
if (!init) {
table = new std::vector<const char*>();
init = true;
}
return (table);
}
// foobar.cpp:
#include <vector>
std::vector<const char*>* getTable();
static struct foo {
foo() { getTable()->push_back("foo"); }
} bar;
// main.cpp:
#include <iostream>
#include <vector>
std::vector<const char*>* getTable();
int main(int argc, char* argv[]) {
std::cout << "size = " << getTable()->size() << std::endl;
return (0);
}
When the three files are compiled and linked together the table gets
populated correctly:
% g++ main.cpp foobar.cpp table.cpp; ./a.out
size = 1
But when table.cpp and foobar.cpp are built into a library and
linked with main.cpp, foobar.cpp gets stripped out:
% g++ -c foobar.cpp table.cpp
% libtool -static -o lib.a foobar.o table.o
% g++ main.cpp lib.a; ./a.out
size = 0
Is there a way to force foobar.o to be linked with the executable so
that the static initialization occurs, without modifying the code?
Many thanks,
Nathan
By default, when you link using a static library, the linker only
include objects that are referenced by you program. As your static
initializer is in an unused object (foobar.o), the linker does not
link it into your executable.
You can tell the compiler to include all objects a static library
contains using the -all_load linker option.
g++ main.cpp -all_load lib.a; ./a.out
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Xcode-users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden