Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "static" needed for a global const char but not for a bool?

Shared header.

I can do this:

const bool kActivatePlayground=false;

Works fine when included among multiple files.

I cannot do this:

const char * kActivePlayground = "kiddiePool";

Results in error: duplicate symbols.

But this works:

static const char * kActivePlayground = "kiddiePool";

Why is the static needed for the const char * but not for the const bool ? Additionally, I thought static is not necessary since const is always static implicity?

like image 613
johnbakers Avatar asked Apr 05 '13 04:04

johnbakers


1 Answers

In C++, const variables by default have static linkage, while non-const variables have external linkage.

The reason for the multiple definitions error is that

const char * kActivePlayground = "kiddiePool";

creates a variable with external linkage.

Hey wait, didn't I just say that const variables default to static linkage? Yes I did. But kActivePlayground is not const. It is a non-const pointer to const char.

This will work as you expect:

const char * const kActivePlayground = "kiddiePool";
like image 95
Ben Voigt Avatar answered Oct 10 '22 22:10

Ben Voigt