2

How can I create a static array in my header file? I looked at some examples on stackoverflow but can't get them to work.

Thanks!

#ifndef DRUMKITLIBRARY_H_
#define DRUMKITLIBRARY_H_


class DrumKitLibrary
{
public:
    static const char* const list[] = {"zip", "zam", "bam"};
};

#endif /* DRUMKITLIBRARY_H_ */
1
  • Which examples did you look at and what didn't work? Commented Nov 24, 2012 at 18:28

2 Answers 2

3

Your compiler error is occurring because that's not how you initialize static data (well, static const integral types can be initialized that way, but that's it). You only declare your static data in the class definition, you define it outside of the class. However, you still have a possible issue.

The problem with defining static data in your header file is that every file which includes that header gets its own copy of the array. You are better served by declaring it in the header and defining it in an implementation file.

// A.h
class A {
public:
    static const char *f[];
};

// A.cpp
#include "A.h"

const char *A::f[] = { "one", "two" };
Sign up to request clarification or add additional context in comments.

1 Comment

@LuchianGrigore: To be honest I'm far from an authority on C++11 and I forgot about constexpr. I pick up tidbits here and there, but I work on embedded software in my day job and we don't yet use a C++11 compiler (FDA guidelines make switching compilers a bit more onerous than one might hope, and we're a small team). Anyway, thanks for mentioning it.
0

You don't.

You declare it in a header and define it in the source.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.