user17481
user17481

Reputation: 763

Export variable from C++ static library

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?

Upvotes: 4

Views: 8634

Answers (3)

Skizz
Skizz

Reputation: 71070

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.

Upvotes: 7

Seb Rose
Seb Rose

Reputation: 3666

You need to declare your Format objects as extern not static

Upvotes: 2

yrp
yrp

Reputation: 4575

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 }

Upvotes: 2

Related Questions