Reputation: 783
I'm writing a library and have some __weak
functions which need to be overwritten by the programmers. I want to make sure they do so, so I did this:
__weak void checkButtons(){
#warning "Implement this"
}
And put the prototype in the header:
__weak void checkButtons();
And implement it in another file:
void checkButtons(){
//Some codes here
}
By the way, the problem is that in compile time, the compiler shows the #warning
message.
compiling library.c...
library.c(8): warning: #1215-D: #warning directive: message "Implement this"
#warning message "Implement this"
library.c: 1 warning, 0 errors
I think if a __weak
function is overridden, the main function should not be compiled, should be?
I don't know why this happens. Any other idea to force the user?
Upvotes: -1
Views: 1480
Reputation: 141180
the main function should not be compiled, should be?
Everything is compiled. Weak functions are compiled, normal functions are compiled. The linker when linking the program chooses (the compiled) normal version of the symbol over the (also compiled) weak version of the symbol. Linking happens after compilation.
why this happens.
You have written a #warning
in your code and it's going to be visible and processed by the compiler anyway, irrelevant if the function is used or not. #warning
s are interpreted by the preprocessor, before compilation.
How to force user implement __weak functions
First, do not use weak
in header file. It would make all function definitions weak that see this declaration.
// header
void checkButtons();
Secondly, if you want to force user to define the function, then don't use weak
and don't define the function. Weak symbols are used when you want to provide a default definition for the function, if you don't want to do it then don't use it. Without function definition, user will receive a "undefined reference"-kind-of error message from the linker.
I'm writing a library and have some functions which need to be overwritten by the programmers
Yet better and normal way would be for your library to take function pointers that point to the functions implemented by the user of your library. Such design is "better" - allows code reuse, easier unit-testing and saves a lot of refactoring in case of later changes.
Upvotes: 3