Problem of declaring a static member in class


I try to declare a structure with static variable.
I got a example from stack overflow but it doesn’t work in ROOT.
Here are the example and the error I got.


class A
      static int x;
int A::x = 100;

ROOT_prompt_4:1:8: error: definition or redeclaration of ‘x’ not allowed inside a function
int A::x = 100;

ROOT Version: 6.10/06
Platform: Ubuntu 14 LTS

I copy/pasted your code in a file called classA.C. It seems to work for me:

$ root
  | Welcome to ROOT 6.15/01              |
  |                                      (c) 1995-2018, The ROOT Team |
  | Built for macosx64                                                |
  | From heads/master@v6-13-04-781-ga796aafe16, Aug 01 2018, 09:10:10 |
  | Try '.help', '.demo', '.license', '.credits', '.quit'/'.q'        |

root [0] .L classA.C
root [1] 

Note that you can only have one variable A::x. So usually you put class A { ... }; in a header file (and add include guards) while the int A::x = 100; goes into the corresponding cpp file (.L this file just once).

Could it be that you are reloading the file or including it multiple times? As Olivier showed, it also works fine if you have everything in one file.

Final question: are you sure you really need a public static variable? It feels like a global variable - and those should be avoided.

With C++17 (not available in Ubuntu 14), you could use an inline static variable instead.

It works for me now.
It seems that this error is caused by other reason.
thank for your help

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.