Declaring a global variable `extern const int` in header but only `int` in source file

三世轮回 提交于 2019-11-28 11:23:09

const int and int are not compatible types.

For example this:

extern const int a;

int a = 2;

is not valid in C as C says that:

(C11, 6.7p4) "All declarations in the same scope that refer to the same object or function shall specify compatible types"

In your case they are not in the same scope (different translation units) but C also says that:

(C11, 6.2.7p2) "All declarations that refer to the same object or function shall have compatible type; otherwise, the behavior is undefined."

As you are violating the rule above, you are invoking undefined behavior.

Note that C90 has the same paragraphs.

A little late, but anyways.

I think this may work if you do something like this

in header.h:

#ifndef HEADER_H_
#define HEADER_H_

#ifndef HAS_GLOB_VAR
extern const int global_variable;
#endif

#endif

and if you need to include the header in the file that actually defines the variable (header.c) you do something like

#define HAS_GLOB_VAR
#include "header.h"

int global_variable = 17;

...

On the other files you just include the header and don't define HAS_GLOB_VAR.

You are not assigning a value to global_variable, you are defining it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!