简体   繁体   中英

Using static variables causes linker error

I get the following error with my code when I compile:

Undefined symbols for architecture x86_64:
  "A::MyNumber", referenced from:
      B::setValue(double) in B.o
ld: symbol(s) not found for architecture x86_64

In A 's header file:

public:
    static double MyNumber;

In A 's class file, above the constructor outside of any functions:

double A::MyNumber = 1.0;

In B 's setValue() function:

#include "A.h"

void B::setValue(double val)
{
    double newVal = val * A::MyNumber;

    ...
}

I'm stumped...I looked at other examples in my project of using static variables and did my best to make sure I did it correctly. The only thing I can think of is that A is in a library that is linked by B 's project.

You have made a typical mistake not to tell the linker about visibility. If you create the library you need to expose so called library symbols. The easiest way to check that is to use nm utility like this (-g means - show extern symbols only):

nm -g <your library>

The solution is quite simple but varies from compiler to compiler. For GCC/CLang it is attribute but almost all support extern . Typical usage looks like that somewhere in your top configuration file:

#if COMPILER_HAS_ATTR_HIDDEN_VISIBILITY   // GCC with -fvisibility=hidden
#define PUBLIC_API            __attribute__((visibility("default")))
#define PRIVATE_API           __attribute__((visibility("hidden")))
#elseif COMPILER_HAS_DECLSPEC_VISIBILITY  // Microsoft C++
#define PUBLIC_API            __declspec(dllexport)
#define PRIVATE_API
#else
#define PUBLIC_API            extern
#define PRIVATE_API
#endif

Now redeclare your class:

// Exposed class
class PUBLIC_API A
{

};

Another question is how to detect that with your building toolchain but that is out of scope of your question. For quick prove - add extern keyword to your class declaration and rebuild the library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM