How can I use a declared but undefined function in C regardless? - c

So what I want to do is I want to create a kind of framework for myself in the future but I realized I can't do something. It goes like this:
void whenPressedQ();
void whenPressedW();
...
void checkPressQ(){
whenPressedQ();
printf("Q was pressed");
}
...
void whenPressedW(){
doThings();
}
Later I will define these functions and choose which of them to use.
Problem is I can't do this for the other functions if I haven't defined them below. I get an "undefined function" error. Is there any way I can solve this? I've tried using pointers to functions and check if it's null but it's the same thing.

You can pass pointers to callback functions, or wrap them in structures, then have the library pass back a pointer to a function that matches the signature later, even one that you will write in the future. This was how the first C++ compilers implemented virtual methods of objects.
If you just want the code to compile while you’re getting around to the unimplemented functions, you can create dummy stub functions to shut the linker up.
Update
Here are some examples of what I mean. Your question is somewhat ambiguous. If what you are asking is how you can declare functions that you intend to implement later, and still be able to compile the program, the answer is to provide stubs. Here’s a MCVE of your interface:
#include <stdio.h>
#include <stdlib.h>
/* In older versions of C, a declaration like void doThings() would turn
* type-checking of function arguments off, like for printf().
*/
void whenPressedQ(void);
void whenPressedW(void);
void doThings(void); // Added this declaration.
void checkPressQ()
{
whenPressedQ();
printf("Q was pressed.\n"); // Don't forget the newline!
}
void whenPressedW()
{
doThings();
}
// Stub implementations:
void whenPressedQ(void)
// FIXME: Print an error message and abort the program.
{
fflush(stdout); // Don't mix the streams!
fprintf( stderr, "Unimplemented function whenPressedQ() called.\n" );
exit(EXIT_FAILURE);
}
void doThings(void)
// Is nothing a thing?
{}
// Test driver:
int main(void)
{
whenPressedW();
whenPressedQ(); // fails;
// Not reached.
return EXIT_SUCCESS;
}
If you want to let the program dynamically select which function to call, that is more complicated, but you can do it with callbacks. Here’s a simple example.
#include <stdio.h>
#include <stdlib.h>
// This would ordinarily go in a .h file:
typedef const char*(*callback_t)(void); // The type of a callback function.
extern callback_t get_the_answer(void);
// This would ordinarily go in a .c file:
int main(void)
{
callback_t ask_the_question = get_the_answer();
printf( "The answer to life, the Universe and Everything is %s.\n",
ask_the_question()
);
return EXIT_SUCCESS;
}
// This would ordinarily go in another .c file:
static const char* the_answer_is(void)
{
return "42";
}
callback_t get_the_answer(void)
{
return &the_answer_is;
}

The error you are getting a linker error. If you are not trying to build an executable, then you can just compile and do not link. On Linux / OS X, you can pass the -c flag to clang or gcc. On Windows, you can pass the /c flag to cl.exe when compiling.
You can then link the object files directly later, or build a static or dynamic library out of them.

Related

How to use REAL function once it is declared as WEAK function in C?

I have a problem when using WEAK reference in C. Make assumption, I have the src code structure as follows:
//Eclipse C project structure
drv
| dummy
| | dummy_Test.h
| | dummy_TestWeakAttribute.h
| src
| | source_sample.c
| test
| | myModules
| strong_test_case.c
| weak_test_case.c
test_program.c
And:
//test_program.c
#include "drv/dummy/dummy_TestWeakAttribute.h"
#include "drv/dummy/dummy_Test.h"
int main() {
printf("===================\n");
printf(" Welcome to main \n");
printf("===================\n");
// Expectation
test(); //-->real function
function(); //-->real function
test_function_strong(); //-->real function
test_function_weak(); //-->weak function
return 0;
}
//source_sample.c
#include "../dummy/dummy_TestWeakAttribute.h"
#include "../dummy/dummy_Test.h"
static void test(void) {
printf("NOT overridden!\n");
}
static void function(void){
int a =1;
a++;
test();
}
//dummy_Test.h
#ifndef DRV_DUMMY_DUMMY_TEST_H_
#define DRV_DUMMY_DUMMY_TEST_H_
#define static
//definitions
//struct definitions
//dummy functions
static void test(void);
static void function(void);
//global variable definitions
#endif /* DRV_DUMMY_DUMMY_TEST_H_ */
//dummy_TestWeakAttribute.h
#define static //disable static keyword
static void __attribute__((weak)) test(void);
//weak_test_case.c
#include "../../dummy/dummy_TestWeakAttribute.h"
#include "../../dummy/dummy_Test.h"
static void test(void){
printf("overridden successfully!\n");
}
void test_function_weak(void){
function();
}
//strong_test_case.c
#include "../../dummy/dummy_Test.h"
void test_function_strong(void){
function();
}
I got the result on the screen:
===================
Welcome to main
===================
overridden successfully!
overridden successfully!
overridden successfully!
overridden successfully!
I can't use the REAL function anymore. All my making calls to the real test function is impossible because it was declared as __attribute__((weak)) before. So, Is there anybody having idea on this case ? The main purpose, I'd like to call my real test (in source_sample.c) but don't remove weak attribute as well.
First off, be aware that weak linkage is not a C concept. It is an ELF concept, at least for our purposes, and GCC (and other compiler) support for it is a C extension. Therefore, little of what I have to say is based on the C standard. With that said ...
Your program has two functions test(), both with weak linkage. If there were an alternative with strong linkage then that would override both. Since there is not, it is unspecified which of the two is linked to any given reference (call), but it follows from the mechanism of ELF dynamic linking that the same one would would be linked to every reference in any given dynamic object.
Other than system libraries, you have only one dynamic object in play -- the program -- so it stands to reason that the same implementation of test() is called at every point. It's unclear to me why you suppose it would be otherwise. Note in particular that the weird games you are playing with the static keyword are strictly obfuscatory. You have no actual static declarations anywhere in the code you present.
You indeed could declare a static function test in some file, and in that case you would expect calls to test() from within that file to be linked to the internal static version. To the best of my knowledge, however, a static function cannot also be weak. That wouldn't make any sense.
The main purpose, I'd like to call my real test (in source_sample.c) but don't remove weak attribute as well.
So you want to provide for overriding some references to the function but not others? Are you nuts? What a nightmare that would be to build, and I don't even want to think about maintaining it.
If you want to provide a default implementation that you can always call then you cannot make that the weak function. Doing so is inconsistent with always being able to call it. You can, however, make it a separate, ordinary function that the weak one calls, and any other function also can call:
test.h:
#ifndef TEST_H
#define TEST_H
void test(void) __attribute__((weak));
void test_default(void);
#endif
test.c:
#include "test.h"
void test_default(void) {
printf("I am the default implementation");
}
void test(void) {
test_default();
}
Anyone with access to test_default() can then call it, but whether it gets called as a result of calling test() depends on what version of test() is linked to the call -- it is weak, so a different version could be provided.
Note also that depending on the scope you want test_default() to have, it might be both possible and sensible to make it static, whereas test() must not be static as long as it is weak.

Dead code removal if implementation is overwritten

I'm in the process of writing a library that provides a sha256 implementation. The library will be given to vendors that may want to provide their own sha256 functions that are optimized for their platform. So, the API of this library allows the client to pass in function pointers to their sha256 code.
int mylib_set_sha256_impl( /* function pointers */ );
Henceforth, all algorithms will use the function pointers provided internally instead of the stock sha256 code provided by the library.
The question is: how can I facilitate dead code removal during link time, such that the default sha256 implementation in this library is removed??
This is an API design question as much as it is a compiler-optimization question.
There are no special requirement as far as linker is concerned, and no weak aliasing need be considered.
The basic rule is: As long as the user code doesn't reference any symbols in a given .c or .s file that you linked into your library, the said file's contents won't end up in the executable.
In the scenario you describe, your functions may never become dead code since your "live" code perhaps references their addresses to set up default function pointer values. To make sure that doesn't happen, you have to do the following:
Refer to the replaceable functions only from within a user-callable optional default_init function.
The default_init must never be called anywhere in your code, neither must any of the functions be referenced anywhere but within default_init.
Have the replaceable functions, and the init function, put into at least one .c or assembly file that is not used for any of the other code.
For your user to replace all the functions, they simply have to never call the default_init function. If you wish functions to be replaceable one-by-one, you have to, additionally:
Have each replaceable function in its own .c file.
Have the user not call the default_init directly, but pass the desired default or user-provided implementations to your init function.
What you're doing, in effect, isn't "overwriting" any implementation, but simply not using it at all.
Example (include guards omitted for clarity):
// api.h
void api_fun1(void);
void api_fun2(void);
void api_default_init(void);
void api_user_init(void (*f1)(void), void (*f2)(void));
void api_use_funs(void);
// api_internal.h
extern void (*api_f1)(void);
extern void (*api_f2)(void);
// common.c
#include "api.h"
#include "api_internal.h"
void (*api_f1)(void);
void (*api_f2)(void);
void api_user_init(void (*f1)(void), void (*f2)(void)) {
api_f1 = f1;
api_f2 = f2;
}
void api_use_funs(void) {
api_f1();
api_f2();
}
// api_fun1.c
#include "api.h"
void api_fun1(void) {}
// api_fun2.c
#include "api.h"
void api_fun2(void) {}
// api_default_init.c
#include "api.h"
#include "api_internal.h"
void api_default_init(void) {
api_f1 = api_fun1;
api_f2 = api_fun2;
}
Let's say that the user wants to override api_fun2 with their own:
// main.c
#include "api.h"
#include <stdio.h>
void my_fun2() {
printf("%s\n", __FUNCTION__);
}
int main() {
api_user_init(api_fun1, my_fun2);
api_use_funs();
}

Violating static function in C

In one interview I was asked, if in one file A, some static function is defined and in file B you want to use this static function -- how you will use it?
My answers were:
declaring in .h file
But if we declare that in a header file, other files which will include this also have access to this static function.
wrapper concept: Declaring a new function newfun in file A, which will call static function and calling this newfun in file B.
But he was not satisfied with these answers.
Can you please provide me some better solution to violate static.
Perhaps they wanted to hear about function pointers?
You can create a pointer to the function, and call it using that pointer.
One possible scenario where this is reasonable is if you have a callback function that you don't want to be callable by everyone, and you give the pointer as an argument to some register_callback function.
Callback functions were used extensively, for example to let the user of a GUI API provide code for what should happen when a button is pressed. Nowadays, with object-oriented languages, it is more common to subclass a class and define or override methods, such as the Android View class and the method OnClickListener, but C# delegates are very similar to C function pointers.
To illustrate the principle, here is the source code (the file "B" in the original question) for some sort of library, where the main component is the do_stuff function:
#include <stdio.h>
#include "some_library.h"
void (*stored_callback)(void) = NULL;
void register_callback(void (*callback)(void)) {
stored_callback = callback;
}
void do_stuff(void) {
printf("Doing stuff...\n");
printf("Calling callback...\n");
if (stored_callback != NULL)
stored_callback();
}
This header, some_library.h, file shows the API of that library:
extern void register_callback(void (*callback)(void));
extern void do_stuff(void);
And here is how the library is used (the file "A" in the question):
#include <stdio.h>
#include "some_library.h"
static void my_callback(void) {
printf("Inside the callback!\n");
}
int main(void) {
register_callback(my_callback);
do_stuff();
return 0;
}
My interview answer would be "You can't."
(Because the question says "in file B you want to use this static function" and it didn't say you are allowed to modify file A.)
I'm assuming you don't have access to the source of the static function or else you could just remove the static keyword or expose the function via an exported wrapper or global function pointer.
You can still use the static function if you use objcopy to manually change the visibility on the symbol in the object file / library.
Suppose this is the (unaccessible) static function:
//static.c
#include <stdio.h>
static void fun(){
puts("Hello world");
}
Suppose you only have static.o, obtainable with gcc -c static.c.
Now, let's assume you want to link static.o with main.o made from
//main.c
void fun();
void main(){
fun();
};
To be able to link it, you need to turn
$ nm static.o
0000000000000000 t fun
U puts
into
0000000000000000 T fun
U puts
You can do that with:
objcopy --globalize-symbol=fun static.o global.o
Now you can link with global.o instead of static.o.
$ gcc main.o global.o && ./a.out
Hello world
filea.c
#include <stdio.h>
#include "filea.h"
static void hidden(void) { printf("inside hidden function.\n"); }
fxptr unhide(void) { return hidden; }
filea.h
#ifndef FILEA_INCLUDED
#define FILEA_INCLUDED
typedef void(*fxptr)(void);
fxptr unhide(void);
#endif
fileb.c
#include "filea.h"
int main(void) {
unhide()();
return 0;
}

why do i need to include a .h header file in the .c file of the same name?

So I'm following along in Head First C and we're on a chapter where we learn to compile multiple files together. One of them is encrypt.c.
#include "encrypt.h"
void encrypt(char *message)
{
char c;
while (*message) {
*message = *message ^ 31;
message++;
}
}
The encrypt.h file repeats the first line with a semicolon at the end, so why do I need it? I understand why I would need header files to fix the problem of using a function before it's defined, so I could understand #including it in a file that uses encrypt.c, but why would I need it inside encrypt.c? Is it just one of those "because" reasons?
If the contents of encrypt.c are shown in their entirety, then you don't need the header. But it's still a good idea to include it because:
If one function in the file uses another, then the order of definition matters because the callee must be defined before the caller. It's even possible to have two functions A and B where each calls the other, in which case you cannot get the code to compile without at least one forward declaration. Including the header with the forward declarations solves these problems.
Consuming the header just like your client code does is a good way to have the compiler point out discrepancies between the signatures in the forward declarations and the actual function definitions. If undetected this kind of problem can lead to "interesting" behavior at runtime and lots of hair-pulling.
You're right, if that's all encrypt.h declares, you don't need to include it in the .c file.
You mostly do it for consistency.
Imagine that you change encrypt.c to void encrypt(char *message, int i) { }
If you don't include encrypt.h you won't notice that the other files in your application haven't been updated to pass the new parameter. If you update encrypt.h and encrypt.c at the same time the compiler can do checking for you.
It's good style.
Sometimes, C-file with function implementation and C-file with function usage shares common declarations - types/structures, This shares declarations places at the H-file.
For ex.
[enc.h]
typedef enum {S,F} Res;
EN encode();
[enc.c]
#include "enc.h"
Res encode() { ... }
[other.c]
Res res;
res = encode();
It is prototyping the function
http://en.wikipedia.org/wiki/Function_prototype
Then you include the header in a another *.c-file the compiler knows in this way that anywhere else is the function definition.
This ist like:
#include <stdio.h>
int main (void)
{
afun();
return 0;
}
void afun (void)
{
printf("hello\n");
}
Now the compiler doesn't know what to do with afun() in the main function. Because it was'nt defined. So it will lead into an compiler error.
So you add the declaration at the beginning or bevore the first usage:
#include <stdio.h>
void afun(void);
int main (void)
{
afun();
return 0;
}
void afun (void)
{
printf("hello\n");
}
Know the compiler knows the deklaration of afun and hopes anythere else the function is defined. With header files it is possible to use precompiled c-code. The only thing the compiler is needed is the deklaration of the function.

Linux function redirect

Hey, I'm trying to wrap a function in my program without using LD_PRELOAD.
I have two functions with the same signature:
void someFunc () {
puts ("someFunc");
}
void someFunc_wrapper () {
puts ("someFunc_wrapper");
}
And I want to redirect any function call to someFunc with a call to the wrapper function.
Of course I could do that with defining macros or put the wrapper function into a shared library and then call the program like this:
LD_PRELOAD=./mylib.so my_program
However, I want to redirect the function calls at runtime, without modifying the program call.
As I understand, it should be possible to redirect these calls by modifying the executable's symbol table at runtime.
Any help will be appreciated :)
ld has the option --wrap=symbol that should do what you want. The manual page has an example how it works.
Even if it is doable, modifying your program's symbol table might not be enough in the general case - think about the compiler inlining your function.
You could do this without dirty tricks by using an indirect function call though (always call that function via a pointer-to-function, update that pointer when you want to switch implementations).
Note that this has some runtime overhead (one more indirection). Whether that's important or not depends on the use case. And it can be turned off at compile time with macro tricks if that's just a debug feature you're implementing.
#include <stdio.h>
void foo(void) {
printf("Hello from foo\n");
}
void bar(void) {
printf("Hello from bar\n");
}
#ifdef INTERCEPT
typedef void(*myfunptr)(void);
myfunptr thingy = foo;
void turnonbar(void)
{
thingy = bar;
}
#else
#define turnonbar()
#define thingy foo
#endif
int main(void) {
thingy();
turnonbar();
thingy();
return 0;
}

Resources