• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
static initialization in a static library
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

static initialization in a static library


  • Subject: static initialization in a static library
  • From: Nathan Litke <email@hidden>
  • Date: Wed, 4 Jun 2008 00:58:39 -0700

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

_______________________________________________
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


  • Follow-Ups:
    • Re: static initialization in a static library
      • From: Jean-Daniel Dupas <email@hidden>
  • Prev by Date: Re: qt4 :rpath can only be used when targeting Mac OS X 10.5 or later
  • Next by Date: Re: static initialization in a static library
  • Previous by thread: Re: qt4 :rpath can only be used when targeting Mac OS X 10.5 or later
  • Next by thread: Re: static initialization in a static library
  • Index(es):
    • Date
    • Thread