ifdef is harmful - but simple workaround is not working
Hi,
I need to write a simple function which will work only when a specific definition is defined, but i can't use ifdef in C file according to linux coding guidelines so i wrote this example but i keep getting this error: file.c: error: redefinition of 'function1' file.h: error: previous definition of 'function1' was here in this example all i want is that function1 will be called only if RUN_FUNC1 is defined, else i want the inline function1 to be called. file.h ... #ifdef RUN_FUNC1 void function1(void); #else static inline void function1(void) { printk("RUN_FUNC1 not defined\n"); }; #endif ... file.c ... void function1(void) { printk("RUN_FUNC1 defined\n",); } ... any ideas? 10x |
The first thing that comes to mind is to declare RUN_FUNC1 as global variable (0 if not defined, anything else - if defined) and use plain if/else inside function. But that won't be possible in all situations.
I'd take a look at any project that is written according to linux coding standarts - to see how they dealt with similar problems. |
Try something like this:
Code:
file.h Code:
... |
According to linux coding guidelines:
No ifdefs in .c Code With the wide number of different processors, different configuration options and variations of the same base hardware types that Linux runs on, it is easy to start having a lot of #ifdef statements in your code. This is not the proper thing to do. Instead, place the #ifdef in a header file, and provide empty inline functions if the code is not to be included. http://www.linuxjournal.com/article/5780 Again, what i'm trying to do is the following: Every time i call function1 and RUN_FUNC1 is defined - I want to run function1 which is defined in file.c Every time i call function1 and RUN_FUNC1 is NOT defined - I want to run the static function1 which is defined in file.h All of these without using ifdef in the c file... I'm sure there are people here who know how... |
This isn't in the context of the kernel, but you get the idea.
Code:
//code.h Code:
//code.c PS Sorry, missed that the static is defined in the header. But why? What other sources need that definition? |
I just can't understand how does this kernel code is compiled...
just look on function hiddev_connect, if CONFIG_USB_HIDDEV is defined, then when calling hiddev_connect - this will call hiddev_connect from hiddev.c and if CONFIG_USB_HIDDEV is not defined, then when calling hiddev_connect - this will call the inline function from hiddev.h why didn't this cause the redefinition error in the compilation?... in include/linux/hiddev.h Code:
#ifdef CONFIG_USB_HIDDEV Code:
int hiddev_connect(struct hid_device *hid) |
Quote:
drivers/hid/usbhid/Makefile: Code:
# Code:
ifeq ($(CONFIG_USB_HIDDEV),y) |
Quote:
Hope this helps. |
Quote:
|
Quote:
|
All times are GMT -5. The time now is 09:03 PM. |