Question

I have a static library written in C++ and I have a structure describing data format, i.e.

struct Format{
    long fmtId;
    long dataChunkSize;
    long headerSize;

    Format(long, long, long);

    bool operator==(Format const & other) const;
};

Some of data formats are widely used, like {fmtId=0, dataChunkSize=128, headerSize=0} and {fmtId=0, dataChunkSize=256, headerSize=0}

Some data structure classes receive format in constructor. I'd like to have some sort of shortcuts for those widely used formats, like a couple of global Format members gFmt128, gFmt256 that I can pass by reference. I instantiate them in a .cpp file like

Format gFmt128(0, 128, 0);

and in .h there is

extern Format gFmt128;

also, I declare Format const & Format::Fmt128(){return gFmt128;} and try to use it in the main module.

But if I try and do it in the main module that uses the lib, the linker complains about unresolved external gFmt128.

How can I make my library 'export' those global vars, so I can use them from other modules?

Was it helpful?

Solution

Don't use the static keyword on global declarations. Here is an article explain the visibility of variables with/without static. The static gives globals internal linkage, that is, only visible in the translation unit they are declared in.

OTHER TIPS

Are they defined in .cpp file as well? Roughly, it should look like:

struct Format
{
    [...]
    static Format gFmt128;
};
// Format.cpp
Format Format::gFmt128 = { 0, 128, 0 }

You need to declare your Format objects as extern not static

Morhveus, I tried this out, too. My linker rather says it has the gFmt128 symbol already defined. This is indeed the behaviour I would expect: the compiler adds the function body to both the library and the client object since it's defined in the include file.

The only way I get unresolved externals is by

  • not adding the static library to the objects-to-be-linked
  • not defining the symbol gFmt128 in the static library's source file

I'm puzzled... How come we see something different? Can you explain what happens?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top