How do I make macro constants globally accessible in C?

半世苍凉 提交于 2021-02-05 09:19:25

问题


I have some macro constants defined in a .c file and a .h file as follows:

#define LOCAL_L2_BASE_LV                                    (0x00800000UL)

in .c file and

#define FPGA_PLI_FEEDBACK_OFFSET_LV_FREQUENCY           (0x00007000UL)

in .h file

I would like to use these constants in a different header file. What is the best way to do so? My initial idea was to use extern in the header file I want to use the constants in, but is this valid?


回答1:


Macros can not be made extern, they are not variables. They are simply textual replacements. To make macros available to other header, you need to include the header defining the macro.




回答2:


You should either put both of the defines in the header file (so that they are visible from any other source file), or define them in the source file as const-qualified variables and use extern in the header file to expose them to the other translation units.

The extern declarations in the header file would look like this:

extern const unsigned long k_local_l2_base_lv;
extern const unsigned long k_fpga_pli_feedback_offset_lv_freq;

You would then define them at the file scope of the source file with external linkage like this:

const unsigned long k_local_l2_base_lv = 0x00800000UL;
const unsigned long k_fpga_pli_feedback_offset_lv_freq = 0x00007000UL;



回答3:


You can't use extern for macros, because they are expanded before linkage.

One way is to create a header with the definitions you need and include it where you need them.

The other way is to pass the definition to the compiler like this (assuming you're using gcc):

gcc -DLOCAL_L2_BASE_LV=0x00800000UL source.c -o executable

The first solution seems better because it keeps the code in the sources (as opposed to the build process).

Additionally, in this specific case the parentheses around the value are not necessary because it forms a single token and it will be expanded as such.



来源:https://stackoverflow.com/questions/33674152/how-do-i-make-macro-constants-globally-accessible-in-c

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