Search code examples
c++compiler-errorsconstantsextern

C++ How to share constants with extern between cpp - Error: storage class specified


I've the header file in which I declare some constants with extern:

#ifndef CONSTANTS_H
#define CONSTANTS_H

#include <string>

class Constants
{
    public:
        Constants(){}
        extern const std::string DELIMITER;
        extern const std::string FILENAME;
        extern const int BLUCAR;
        extern const int REDCAR;
        extern const int EMPTY;
        extern const int SPARSE_LIM;
    protected:
    private:
};

#endif // CONSTANTS_H

Then in the source I define them like this:

#include "constants.h"

extern const std::string DELIMITER = ",";
extern const std::string FILENAME = "cars.csv";
extern const int BLUCAR = 1;
extern const int REDCAR = 2;
extern const int EMPTY = 0;
extern const int SPARSE_LIM = 5;

Why the compiler gives me Error: storage class specified for 'DELIMITER'?


Solution

  • Firstly, these don't seem to be class members. The way you're using extern it looks like you intended for these to be free. Perhaps in a namespace. Take them out of that class.

    Then, when you define them, leave out the extern.

    In this context it means "find this variable elsewhere". You don't want to find it elsewhere. It's here!

    // Header
    namespace Constants {
       extern const std::string DELIMITER;
       extern const std::string FILENAME;
       extern const int         BLUCAR;
       extern const int         REDCAR;
       extern const int         EMPTY;
       extern const int         SPARSE_LIM;
    }
    
    
    // Source
    namespace Constants {
       const std::string DELIMITER  = ",";
       const std::string FILENAME   = "cars.csv";
       const int         BLUCAR     = 1;
       const int         REDCAR     = 2;
       const int         EMPTY      = 0;
       const int         SPARSE_LIM = 5;
    }
    

    Remember, you'd do the same for static object definitions!