Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export variable from C++ static library

Tags:

c++

export

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?

like image 249
user17481 Avatar asked Sep 14 '25 18:09

user17481


2 Answers

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.

like image 145
Skizz Avatar answered Sep 17 '25 09:09

Skizz


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 }
like image 39
yrp Avatar answered Sep 17 '25 08:09

yrp