What are some use cases of do nothing function (in C) like:
dummy() {}
I am reading "The C programming Language" by K&R and in chapter 4 (Functions & Program Structures) , it mentions that
A do-nothing function like this (shown above) sometimes useful as a place holder during program development.
Can anyone explain what author means by that and uses of these types of functions?
A function that does nothing (yet) is an indicator that something should be done, but hasn't been implemented yet.
Have a look at programming idioms like "Skeleton", "dummy code", "mock objects", etc. It is a very common technic that let you test the whole architecture of your program without having implement every details.
Suppose you have an application that is able to save results in a file by calling a function save(), you would like to be able to test the application without the necessity to really save results into a file. So the function save() can be, in a first approximation an empty one! It is very common to write like (pseudo-code here):
save() {
print "save() not yet implemented";
}
to be able to track the calls.
You already have received the answer(s), but just to elaborate on why part, let me add my two cents.
If you try to use a function (call a function) which does not have a definition, linker will throw undefined reference error, because it will not able able to find the actual function definition anywhere in the given object file(s) to link to.
So, sometimes in the development phase, when you need to call an API which is yet to be implemented (or not available till time), a dummy function definition is added, which
either does nothing meaningful
or returns a fixed value
just to compile and check (test) the working of the caller function (module). Without the dummy function definition, the code for the caller function will throw the error.
When you're writing code to explain something, it is better to omit secondary functions, so the reader focuses on the problem and not on the details.
Instead when you write a real program I prefer to create the secondary functions first, test them and alter set all focus on the mainstream.
Related
Can a function tell what's calling it, through the use of memory addresses maybe? For example, function foo(); gets data on whether it is being called in main(); rather than some other function?
If so, is it possible to change the content of foo(); based on what is calling it?
Example:
int foo()
{
if (being called from main())
printf("Hello\n");
if (being called from some other function)
printf("Goodbye\n");
}
This question might be kind of out there, but is there some sort of C trickery that can make this possible?
For highly optimized C it doesn't really make sense. The harder the compiler tries to optimize the less the final executable resembles the source code (especially for link-time code generation where the old "separate compilation units" problem no longer prevents lots of optimizations). At least in theory (but often in practice for some compilers) functions that existed in the source code may not exist in the final executable (e.g. may have been inlined into their caller); functions that didn't exist in the source code may be generated (e.g. compiler detects common sequences in many functions and "out-lines" them into a new function to avoid code duplication); and functions may be replaced by data (e.g. an "int abcd(uint8_t a, uint8_t b)" replaced by a abcd_table[a][b] lookup table).
For strict C (no extensions or hacks), no. It simply can't support anything like this because it can't expect that (for any compiler including future compilers that don't exist yet) the final output/executable resembles the source code.
An implementation defined extension, or even just a hack involving inline assembly, may be "technically possible" (especially if the compiler doesn't optimize the code well). The most likely approach would be to (ab)use debugging information to determine the caller from "what the function should return to when it returns".
A better way for a compiler to support a hypothetical extension like this may be for the compiler to use some of the optimizations I mentioned - specifically, split the original foo() into 2 separate versions where one version is only ever called from main() and the other version is used for other callers. This has the bonus of letting the compiler optimize out the branches too - it could become like int foo_when_called_from_main() { printf("Hello\n"); }, which could be inlined directly into the caller, so that neither version of foo exists in the final executable. Of course if foo() had other code that's used by all callers then that common code could be lifted out into a new function rather than duplicating it (e.g. so it might become like int foo_when_called_from_main() { printf("Hello\n"); foo_common_code(); }).
There probably isn't any hypothetical compiler that works like that, but there's no real reason you can't do these same optimizations yourself (and have it work on all compilers).
Note: Yes, this was just a crafty way of suggesting that you can/should refactor the code so that it doesn't need to know which function is calling it.
Knowing who called a specific function is essentially what a stack trace is visualizing. There are no general standard way of extracting that though. In theory one could write code that targeted each system type the software would run on, and implement a stack trace function for each of them. In that case you could examine the stack and see what is before the current function.
But with all that said and done, the question you should probably ask is why? Writing a function that functions in a specific way when called from a specific function is not well isolated logic. Instead you could consider passing in a parameter to the function that caused the change in logic. That would also make the result more testable and reliable.
How to actually extract a stack trace has already received many answers here: How can one grab a stack trace in C?
I think if loop in C cannot have a condition as you have mentioned.
If you want to check whether this function is called from main(), you have to do the printf statement in the main() and also at the other function.
I don't really know what you are trying to achieve but according to what I understood, what you can do is each function will pass an additional argument that would uniquely identify that function in form of a character array, integer or enumeration.
for example:
enum function{main, add, sub, div, mul};
and call functions like:
add(3,5,main);//adds 3 and 5. called from main
changes to the code would be typical like if you are adding more functions. but it's an easier way to do it.
No. The C language does not support obtaining the name or other information of who called a function.
As all other answers show, this can only be obtained using external tools, for example that use stack traces and compiler/linker emitted symbol tables.
Let's say I have a function:
int foo (int A, char B){...}
One of the features I want to implement is the capability for the user to call any function on the application through the Linux terminal. So as an input for the software, in the terminal they type something like:
foo 2 'a'
Then my application parses that, and using the symbol tables it is able to find the address for foo(), as well as the type for all its parameters.
However, I'm not sure how I would pass the parameters to the function when calling it, since I can have hundreds of different parameters types combination depending on the function called.
Any hint how that could be achieved without having hundreds of nested if statements to cast the parameters to the correct types before calling the functions?
That functionality is similar to what GDB has, where you can do call foo(2,'a') and GDB calls that function to you.
There are two approaches to this. If what you described is all you want to do, then you can use the dyncall library so that you dont have to worry about platform/compiler-specific calling semantics yourself:
The dyncall library encapsulates architecture-, OS- and compiler-specific function call semantics in a virtual bind argument parameters from left to right and then call interface allowing programmers to call C functions in a completely dynamic manner. In other words, instead of calling a function directly, the dyncall library provides a mechanism to push the function parameters manually and to issue the call afterwards.
The other approach is, if you might want to do more: e.g. what if an argument cannot be created by a literal? What if the argument is the output of another function? Can you write f(123, g("a")) in your console? Can you write x=g("a"); f(x)? And if(cond) x="a" else x="b"; f(x) In this case you need to embed a scripting language like e.g. LUA.
If you compile your binary with debug information, you can extract it using libdwarf (https://www.prevanders.net/dwarf.html), so for every function you can get a list a parameters with types and you would know how to interpret user's input.
I am new to RTOS and I was going through some demo code in freeRTOS, I came across xtaskcreate function.I know that when a function is called it should have its function body some where in the code.When I referred the the task.c file and did not found any xtaskcreate function body. So can some one explain me where the xtaskcreat function body is present else if not then how it is executed.
It's defined in file Source/tasks.c near line 595 (FreeRTOS v9.0.0rc2).
But if SUPPORT_DYNAMIC_ALLOCACTION is not defined, xTaskCreate won't be defined too.
It depends which FreeRTOS version you are using.
The latest V9.0.0rc2 has both xTaskCreate() and xTaskCreateStatic() as separate functions in tasks.c. Some versions will have both calls defined as macros that each calls xTaskGenericCreate() with parameters set appropriately for the required behavior (hiding the complexity from the end user).
In both cases its easy to find out. The 'Task' on the front of the function name tells you the prototype is in tasks.h - so just search that file for xTaskCreate() and see if it is a direct function call or a macro that calls another function - which you can then find in tasks.c.
I have a use-case in which the function contents are to be selected conditionally. And that function pointer is passed to other module for later invocation.
void encode_function(int flag)
{
if (flag == 1)
encode1();
if (flag == 2)
encode2();
encode_defaults();
}
Once the encode_function() is populated, I will pass it to other module, where it will be invoked.
I am trying to achieve it in C language, but no success so far. I tried to look at dyncall library but it supports only dynamic parameter changes.
I am looking for something which allows me to change the function contents at run-time.
Some existing question Is there a way to modify the code of a function in a Linux C program at runtime?
You are basically looking for the ability to treat code as data, which is a feature rarely available in compiled imperative static languages like c. The capability of modifying functions at run time is generally categorized as high order functions (you're basically trying to return a function as data somewhere in the code).
If the problem can be solved by several static functions, you can pass in function pointers to different implementations, otherwise I think c does not have the ability to really treat code as data and modify them on the fly.
This question makes attempt to implement high order function in c, but going this far might not be what you want.
I'm currently building a lua event system (in lua), however I want to be able to fire events from C too, I was wanting to bind a C function to a lua function, such that the C function could fire events in lua, I was planning to use the:
lua_register
function; however I can't seem to find a way to bind my lua function like this, it would seem I'm in need of a lua function that does the same, but from the lua side, I was thinking about making some hack, by binding a C function into lua, that simply calls 'lua_register', but this seems a bit unsafe to me.
So what should I do instead?
I'm not fully sure I understand what you've asked for. So allow me to explain what I think your question is.
You have some Lua code. In that Lua code, you have a system. This system is, at some point, given one or more events. For each event that it is given, it calls some function or functions that were registered to be called when that particular event was given.
So, this system has two basic functions:
EventSystem:RegisterEventHandler(EventName, Func);
EventSystem:FireEvent(EventName, ...);
The RegisterEventHandler method will associate the given Func with the given EventName, such that when FireEvent is called later, Func will be called if the EventName given to FireEvent is the same one Func was registered with.
Now you want to have C code be able to register C functions as event handlers. So it's time to talk about registering C functions in Lua.
The C API call lua_register is actually a macro. It creates a C function on the Lua stack, then puts it in the global table, using the string index given to lua_register. These are two separate operations; lua_register is just a convenience function that makes them the same.
What you want is to call RegisterEventHandler from C code, passing the C function as the third parameter (remember: the first parameter is self, because I called RegisterEventHandler with : instead of .. If you're using a global event system rather than an object oriented one, you only have two parameters). This requires two things:
You have to know how to call Lua functions from C code.
You have to know how to pass a C function to Lua code.
Step 1: It's all done via the Lua stack (I'll assume you know how that works. If not, I have a pretty substantial answer that explains most everything you might want to know about it).
The first thing you need to do is get the function you want to call onto the stack. To do that, you need to get an event system object (again, if your event system is global, just get the global table) and push it onto the stack. How you do that depends on where your event system objects are stored. Presumably you can get them through the global table.
Once you have the event system on the stack, you just index it with the "RegisterEventHandler" string, which will return to you the Lua function we need.
Next, we push our parameters onto the stack, from first to last. The first parameter is the event system object; it's probably still on the stack, so we can copy it. The second is the event name, and that's easy to push. The third is the C function. Which leads us to:
Step 2: lua_register is not going to get the job done. It's too heavy handed; it puts the C function in the global table. We need it on the stack. So we must use a lower level function: lua_pushcclosure. Or lua_pushcfunction, if you don't need upvalues.
These functions take a C function, wrap it up in Lua, and push it onto the Lua stack.
Now that the 3 parameters are on the stack, we can call the event registration function with a call to lua_pcall. Or your favorite Lua function calling function; however you wish to do it. Lua will consume the 3 parameters and the function itself, so that they are no longer on the stack.
And since the event registration function probably doesn't return values, the stack will be where it was right before we got the function onto the stack (but not before we started, depending on how much cleanup was done while getting the function).
After this, your C function will be registered with the event handler for that event name.