C++ static const multiple declaration error in Ecl

2019-08-12 05:27发布

I've read the similar questions, but the one that answers mine applies only to VisualStudio. I am using Eclipse and developing an Android application using Cocos2d-X, which is a framework that uses Android's NDK. I created a class named Config, which contains all of the application's constants such as ball sizes and fps. Below is how I arranged the code.

Config.h

#ifndef __CONFIG_H_ // this was auto-generated by eclipse
#define __CONFIG_H_

class Config {
public:
    static const double GRAVITY;
    static const int BALL_WIDTH;
    static const int BALL_HEIGHT;
}

#endif /* config.h */

Config.cpp

#include "Config.h"


const double Config::GRAVITY = 9.8;
const int Config::BALL_WIDTH = 100;
const int Config::BALL_HEIGHT = 100;

It compiles without errors, but when it begins linking, I get the following error:

multiple definition of `Config::GRAVITY'
C:/workspace/cocos2d-x/SampleGame/android/obj/local/armeabi/objs-debug/game/../../../Classes/Config.o:(.rodata+0xc8): first defined here
C:/workspace/cocos2d-x/SampleGame/android/obj/local/armeabi/objs-debug/game/../../../Classes/Ball.o:(.rodata+0xcc):`

The previous error occurs for all the constants declared. I have not included Config.cpp in the source code of any of the reported source files.

I have no idea how to correct this. I found an extremely similar question, but the answer was specified towards Microsoft's VisualStudio. Also, I'm sorry for using the 'cocos2d' tag, even if this applies to cocos2d-X, but I'm hoping someone knows how to fix this.

2条回答
男人必须洒脱
2楼-- · 2019-08-12 05:53

In your case, the names doesn't match. You are declaring as gravity and in cpp it's GRAVITY.

Edit: After your edit, I see no linking errors in your code unless you have defined GRAVITY in your Ball.cpp/h file also.

查看更多
放我归山
3楼-- · 2019-08-12 06:10

The only way that error could occur is if you're including the .cpp file around. Else, your code is perfectly Standards-compliant. After all, the error implies that the constant was defined in Ball.o, which I find very unlikely unless you included the cpp.

查看更多
登录 后发表回答