I was trying to implement access specifier (not sure if that is called access specifier)
The purpose is to make a function (func2) callable only at one place(inside func1).
int func1 ()
{
// Make func2 callable only here`
#define FUNC2_CALLABLE
func2();
#undef FUNC2_CALLABLE
}
#ifdef FUNC2_CALLABLE
int func2 ()
{
return 1;
}
#endif // FUNC2_CALLABLE
func2 should be callable only from func1 and not from any other place in the code.
Does the above code serve the purpose ? Any alternative suggestions
< Edit 1 >
How about doing it this way
int func2()
{
#ifdef FUNC2_CALLABLE
return 1;
#endif
}
Will this work ?
< / Edit 1>
That will give you a linker error of func2 not found (func2 won't be defined if you use that).
I think you might be looking for static.
static int fake(int x) { return x * 2; }
int doSomething(int x) { int tmp = fake(x); doOtherThings(); }
The fake would not exist outside of the compilation unit (file basically).
As for allowing a function to only be called from another function, that doesn't make much sense. Just inline the code if that's your end goal.
There is no real way to do it. The best that can be done in standard C is to make func2 static and define it close to the bottom of the source file:
static int func2 ()
{
return 1;
}
int func1 ()
{
func2();
}
(end of file)
Maybe you can use static keyword .
But the function with static is accessible for all the code in the same file. Other files cannot access it.
Related
Let's assume I have 2 functions other than the main(), respectively func1() and func2(). Is it possible for me to call func1() in func(2) without declaring it first? Or should I use a pointer to the other function and pass it as an argument? Thanks in advance.
_"Is it possible for me to call func1() in func(2) without declaring it first?"_
It depends on compiler, but generally this will not work. (see exclusion example at bottom of answer.)
Some scenarios that illustrate:
Scenario 1: Normally will not work as function is being referenced before being declared:
int main(void)
{
int ret = func1();
return 0;
}
int func1(void)
{
return 1;
}
int func2(void)
{
return func1();
}
Results:
9, 15 error: implicit declaration of function 'func1' is invalid
in C99. Make sure that you include the function prototype.
Scenario 2: As all required definitions occur in order, this will compile and run without issue:
char func1(void)
{
return 1;
}
char func2(void)
{
return func1();
}
int main(void)
{
char ret = func1();
ret = func2();
return 0;
}
Results:
Compiles and runs with no problem because both functions are defined before being called (both func2() called from main() and func1() called from func1)
Scenario 3: The best way is always to pre-declare functions using prototypes either in same file before functions are called or in a header file that is #included in any source file that uses them. This clears up any potential problems, especially for those that inherit the code for maintenance:
int func1(void);
int func2(void);
int main(void)
{
int ret = func1();
return 0;
}
int func1(void)
{
return 1;
}
int func2(void)
{
return func1();
}
Regarding your comment:
"...a statement in my book caused confusion, I thought it might be related to a difference of the version of the C compiler in the book and I am using."
Could be: Per comment below, pre-standard C function definitions are supported by some modern compilers (eg gcc) thus would compile scenarios 1 & 2 without issue if functions complied with the default function definition; eg:
int func1(void)
int func2(void)
Here is how you do it:
void func2(int code); // forward declaration
void func1(const char* str)
{
func2(str[0]); // a call to a declared function
}
void func2(int code) // the callee
{
printf("code: %d\n", code);
}
I'd like to inline some functions, however, they are shared across the team and I don't want to force people to use them.
What would be the best way to add inline versions?
// normal
int func1();
int func2();
// inline versions
inline int inl_func1() { ... }
inline int inl_func2() { ... }
Would something like that make sense?
Edit:
Ideally:
I wouldn't have to write the same function definitions (function body) twice.
It would all be handled with s single define.
Declare/define the inline version and declare the non-inline version in the header file with different names.
// "func.h"
// normal
int func1(void);
int func2(void);
// inline versions
static inline int func1_inline(void) { ... }
static inline int func2_inline(void) { ... }
This allows a user to use either form or both. There is little compelling reason to use the same name and only allow one form.
Both can be handy for code that needs speed vs. space on some calls and not others.
This has a benefit that the one .c file that defines/implements func1(), func2() can use simple code to insure equivalent functionality.
#include "func.h"
int func1(void) {
return func1_inline();
}
int func2(void) {
return func2_inline();
}
BTW, declaring a function like int func1(); does not mean the same as int func1(void);. int func1(); means func1 returns an int, but provids no information about what can be passed to it. It is more like pseudo-code int func1(...);
Perhaps you could tell the people who want the inline functions to define a specific macro before including your header file:
#define WANT_INLINE_FUNC1
#include "awesome_funcs.h"
People who want the to call the externally linked function should omit the macro:
#include "awesome_funcs.h"
Then, in "awesome_funcs.h":
#ifdef WANT_INLINE_FUNC1
inline int func1(int param)
{
/* function body here */
}
#else
extern int func1(int param);
#endif
You also need to define a copy of the function with external linkage in one of your library files, e.g. in "awesome_funcs.c":
#define WANT_INLINE_FUNC1
#include "awesome_funcs.h"
/*
* This will define func1 with external linkage,
* but the function body is copied from the inline definition
* in "awesome_funcs.h".
*/
extern int func1(int param);
EDIT 1
You could combine this with chux's answer and get the best of both worlds (unless that makes things too confusing for your users). Just replace func1 in "awesome_funcs.h" with the following:
static inline int inl_func1(int param)
{
/* function body here */
}
#ifdef WANT_INLINE_FUNC1
inline int func1(int param)
{
return inl_func1(param);
}
#else
extern int func1(int param);
#endif
Then inl_func1 will always be the inline version, and func1 may or may not be inline, depending on whether or not the WANT_INLINE_FUNC1 macro was defined before including "awesome_funcs.h".
What would be the best way to add inline versions?
Your easiest course of action would be to declare static inline versions of these functions:
static inline int func1() { ... }
static inline int func3() { ... }
The function names do not need to differ from those of the corresponding external functions. However, if you #include a header that has declarations of functions with those names, then they must be compatible, AND there must be prior static declarations. For example:
static inline int func1(/* params */);
static inline int func3(/* params */);
#include "our_functions.h"
// ...
static inline int func1(/* params */) {
// implementation ...
}
static inline int func3(/* params */) {
// implementation ...
}
This will allow you to add inline versions without modifying your existing code that calls the external versions of these functions, and without affecting any other translation units. There is at least one alternative, but I don't see anything to recommend it over the above for your particular circumstances.
I'm trying to call other adjacent functions (delay() and delay_ex()) from a function (bitcheck()) as shown below and as expected, the compiler has thrown an error that delay() and delay_ex() functions weren't declared in the scope and I understood that we can't call functions other than from the main. So, I declared these delay() and delay_ex() functions in a header file and called from this program by including the header file, it worked well. So, is there any other such way to make this work?
void bitcheck()
{
int i;
for(i=0;i<NELEMS(array); i++)
{
delay();
AP_CMU->DIVIDER = freq_def[0];
encryption(array,i);
delay();
// LCD_DisplayUint32(i,0,array[i]);
AP_CMU->DIVIDER = freq_def[6];
delay_ex(10);
decryption(intr_array,i);
delay_ex(10);
// LCD_DisplayUint32(i,10,array[i]);
}
}
void delay()
{
int i;
for (i = 0; i < 100000; i++) {
__NOP();
}
}
void delay_ex(int j)
{
for(int s=0; s < j; s++)
{
for ( int i = 0; i < 10000; i++) {
__NOP();
}
}
}
You can write your functions above the code that calls them like:
void foo() {
}
void bar() {
}
int main () {
foo();
bar();
}
You can also forward declare functions like:
void foo();
void bar();
int main () {
foo();
bar();
}
void foo() {
}
void bar() {
}
Or you can put them in a header file and include it
file.h:
void foo();
void bar();
file.c:
#include "file.h"
int main () {
foo();
bar();
}
void foo() {
}
void bar() {
}
The compiler works in a single pass, as such when bitcheck() is parsed, the signatures of delay() and delay_ex() are not known, so the compiler cannot verify the call is type-correct.
The rule is declare or define before use; there are two possible solutions:
Define bitcheck() after the definition of delay() and delay_ex()
Forward-declare delay() and delay_ex().
By declaring the functions in a header and including it before defining bitcheck(), you used the second of these solutions, but use of an include file was not essential - #include does noting more than insert the file content into the translation-unit prior to compilation. This is useful when the symbols will be called from a different translation-unit than that in which they are defined; if that is not intended the declarations may be written directly rather then #include'd, and should also be declared static to avoid external-linkage and potential name clashes with other translation-units.
You need to define delay and delay_ex before bitcheck. Simply moving those two functions above bitcheck should suffice.
In the C language, __FUNCTION__ can be used to get the current function's name.
But if I define a function named a() and it is called in b(), like below:
b()
{
a();
}
Now, in the source code, there are lots of functions like b() that call a(), e.g. c(), d(), e()...
Is it possible, within a(), to add some code to detect the name of the function that called a()?
Further:
Sorry for the misleading typo. I have corrected it.
I am trying to find out which function calls a() for debugging purposes. I
don't know how you do when in the same situation?
And my code is under vxWorks, but I am not sure whether it is related to C99 or
something else.
There's nothing you can do only in a.
However, with a simple standard macro trick, you can achieve what you want, IIUC showing the name of the caller.
void a()
{
/* Your code */
}
void a_special( char const * caller_name )
{
printf( "a was called from %s", caller_name );
a();
}
#define a() a_special(__func__)
void b()
{
a();
}
You can do it with a gcc builtin.
void * __builtin_return_address(int level)
The following way should print the immediate caller of a function a().
Example:
a() {
printf ("Caller name: %pS\n", __builtin_return_address(0));
}
If you are using Linux system, you can use the backtrace() function.
See the man page for more details and a code example.
Try this:
void a(<all param declarations to a()>);
#ifdef DEBUG
# define a(<all params to a()>) a_debug(<all params a()>, __FUNCTION__)
void a_debug(<all params to a()>, const char * calledby);
#endif
void b(void)
{
a(<all values to a()>);
}
#ifdef DEBUG
# undef a
#endif
void a(<all param declarations to a()>)
{
printf("'%s' called\n", __FUNCTION__);
}
#ifdef DEBUG
void a_debug(<all param declarations to a()>, const char * calledby)
{
printf("'%s' calledby '%s'", __FUNCTION__, calledby);
a(<all params to a()>);
}
#endif
If for example <all param declarations to a()> is int i, double d, void * p then <all params to a()> is i, d, p.
Or (less evil ;->> - but more code modding, as each call to a() needs to be touched):
void a((<all params of normal a()>
#ifdef DEBUG
, const char * calledby
#endif
);
void a((<all params of normal a()>
#ifdef DEBUG
, const char * calledby
#endif
)
{
#ifdef DEBUG
printf("'%s' calledby '%s', __FUNCTION__, calledby);
#endif
...
}
...
void b(void)
{
a(<all params of normal a()>
#ifdef DEBUG
, __FUNC__
#endif
);
}
__FUNCTION__ is available on GCC (at least?), if using a different C99 compiler replace it with __func__.
Refer: https://www.gnu.org/software/libc/manual/html_node/Backtraces.html
A backtrace is a list of the function calls that are currently active
in a thread. The usual way to inspect a backtrace of a program is to
use an external debugger such as gdb. However, sometimes it is useful
to obtain a backtrace programmatically from within a program, e.g.,
for the purposes of logging or diagnostics.
The header file execinfo.h declares three functions that obtain and
manipulate backtraces of the current thread.
If you're only after knowing where you were for logging/debug purposes you can use a macro to avoid __func__ giving the name of your logging/debug function but of the function calling it.
Being in a macro will not result in a change to __func__ but will "feel" like using a function.
e.g.
#define LOG(s, data...) log("%s: "s, __function__, ## data)
If your platform is Windows, you may use this: walking the callstack
You can tag each function that calls a() with an integer identifier which is passed to a() as a parameter and then use a switch-case construct in a() to tell which function has invoked a().A printf() would tell which function invoked a() depending on the integer identifier value if you use that as an argument to a switch-case construct in a()
#include<stdio.h>
void a(int);
void b();
void c();
void d();
int main(void)
{
b();
c();
d();
}
void b()
{
int x=1;
a(x);
}
void c()
{
int x=2;
a(x);
}
void d()
{
int x=3;
a(x);
}
void a(int x)
{
switch(x)
{
case 1:
printf("b called me\n");
break;
case 2:
printf("c called me\n");
break;
case 3:
printf("d called me\n");
}
}
If the function in question is in a different c file, you can do
#define name_of_function(...) \
printf("Function %s is parent\n", __FUNCTION__); \
name_of_function(__VA_ARGS__);
And at the top of the c file it lives in
#ifdef name_of_function
#undef name_of_function
#endif
If they're in the same file, you can wrap the function definition in the second macro, then redefine the first macro at the end.
It's not terribly extensible because you can't generate new defines from other defines, but if you're trying to track down parents for a particular function it works without any nonsense.
https://godbolt.org/z/f2jKOm
#include <stdio.h>
#include <stdlib.h>
#define FUNCTION_NAME(FUNCTION) printf("FUNCTION=%s \r\n", #FUNCTION);
int a() {
printf("A function call");
}
int b() {
printf("B function call");
}
int main(){
FUNCTION_NAME(a);
FUNCTION_NAME(b);
return 0;
}
I need to provide a C static library to the client and need to be able to make a struct definition unavailable. On top of that I need to be able to execute code before the main at library initialization using a global variable.
Here's my code:
private.h
#ifndef PRIVATE_H
#define PRIVATE_H
typedef struct TEST test;
#endif
private.c (this should end up in a static library)
#include "private.h"
#include <stdio.h>
struct TEST
{
TEST()
{
printf("Execute before main and have to be unavailable to the user.\n");
}
int a; // Can be modified by the user
int b; // Can be modified by the user
int c; // Can be modified by the user
} TEST;
main.c
test t;
int main( void )
{
t.a = 0;
t.b = 0;
t.c = 0;
return 0;
}
Obviously this code doesn't work... but show what I need to do... Anybody knows how to make this work? I google quite a bit but can't find an answer, any help would be greatly appreciated.
TIA!
If you're using gcc you can use the constructor attribute,
void runs_before_main(void) __attribute__((constructor))
{
...
}
From the gcc documentation
The constructor attribute causes the
function to be called automatically
be- fore execution enters main ().
Similarly, the destructor attribute
causes the function to be called
automatically after main () has
completed or exit () has been called.
Functions with these attributes are
useful for initializing data that will
be used implicitly during the
execution of the program.
You may provide an optional integer
priority to control the order in which
constructor and destructor functions
are run. A constructor with a smaller
priority number runs before a
constructor with a larger priority
number; the opposite relationship
holds for destructors. So, if you have
a constructor that allocates a
resource and a destructor that
deallocates the same resource, both
functions typically have the same
priority. The priorities for
constructor and destructor functions
are the same as those specified for
namespace-scope C++ objects
If you want to hide a struct from users, declare the struct in a header but define it in the c file, passing around pointers. As an example:
// foo.h
typedef struct private_foo foo;
foo * create_foo(void);
void free_foo(foo * f);
// foo.c
struct private_foo {
int i;
}
foo * create_foo(void){
foo * f = malloc(sizeof(*foo));
if (f) f->i = 1;
return f;
}
...
foo->i can then not be accessed outside foo.c.
If you want the client code to be able to use "t.a = ...", then you cannot hide the struct definition. What you want is called an opaque type, that will look something like this:
public.h:
struct foo;
set_a( struct foo *, int );
struct foo * new_foo(void);
main.c:
#include <public.h>
int main( void )
{
struct foo *k;
k = new_foo();
set_a( k, 5 );
}
The structure definition is only available to the library. If you do not make the library source code available, it is possible to completely hide it from the users of the library.
There is no portable way in C to ensure your code will run before main(). What I would do is just maintain an initialised flag in your library, set to false, and then refuse to do anything until your init function has been called.
As in:
static int initialised = 0;
int init (void) {
// do something.
initialised = 1;
return ERR_OK;
}
int all_other_functions (void) {
if (!init)
return ERR_NOT_INITED;
// do something.
return ERR_OK;
}