Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make macro constants globally accessible in C?

Tags:

c

macros

extern

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?

like image 920
Farhan Ahmed Wasim Avatar asked Jan 26 '26 10:01

Farhan Ahmed Wasim


2 Answers

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.

like image 157
SergeyA Avatar answered Jan 28 '26 01:01

SergeyA


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;
like image 42
Blagovest Buyukliev Avatar answered Jan 28 '26 01:01

Blagovest Buyukliev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!