We have been compiling a library on both Linux (gcc) and Windows (Visual Studio), and as expected, finding minor, but not significant differences between what it takes to get a clean compile on both platforms.
Today, I changed gcc compiler flag to use -fPIC
(to enable making a shared library). When we tested linking a program against the library, we started getting errors (for the first time), with undefined reference
to 2 static constants which are declared and initialized in the header file (but not in .cpp file).
I found this StackOverflow answer which seemed to address the problem, explaining that, even if static const
is initialized in header file, it still needs to be defined in the code file. And making that change did remove the gcc linker error.
Visual Studio, however, didn't like that change, and generated multiple definition
errors. We had to wrap the definition needed a preprocessor conditional to get Visual Studio to compile cleanly.
Can someone enlighten me as to what the difference is here? (Code excerpt is below.)
msg.h
class msg
{
public:
static const int EMPTY_INT_VALUE = INT_MAX;
static const char EMPTY_STRING_VALUE = '\002';
// can't define value in header, defined in cpp file
static const double EMPTY_DOUBLE_VALUE;
...
}
msg.cpp
#include "msg.h"
const double msg::EMPTY_DOUBLE_VALUE(DBL_MAX);
#ifndef _WIN32
// g++ requires these definitions, vs 2010 doesn't like them
const int msg::EMPTY_INT_VALUE;
const char msg::EMPTY_STRING_VALUE;
#endif