Export variable from C ++ static library

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

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

    Format(long, long, long);

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

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

Some data structure classes get the format in the constructor. I would like to have some shortcuts for those commonly used formats, like a pair of global Formatmembers gFmt128, gFmt256that I can pass by reference. I create them in a .cpp file, for example

Format gFmt128(0, 128, 0);

and in .h there

extern Format gFmt128;

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

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

"" , ?

+3
4

. / . , , .

+7

.cpp? , :

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

extern static

+2
Morpheus, I tried it too. My linker rather says it already has a gFmt128 character defined. This is really the behavior I would expect: the compiler adds the function body to both the library and the client object, as it is defined in the included file.

The only way to get unresolved external values ​​is

  • do not add a static library to related objects
  • does not define the gFmt128 symbol in the static library source file

I am puzzled ... Why are we seeing something else? Can you explain what is going on?

+1
source

Source: https://habr.com/ru/post/1697114/


All Articles