I would like a function that is not a member of a class and is accessible from any class.
I assume I would have to #include
the header file where the function is declared, but I don't know where to define such a global function.
Are there good reasons against having such a function in the first place?
The variables that are declared outside the given function are known as global variables. These do not stay limited to a specific function- which means that one can use any given function to not only access but also modify the global variables.
If you define functions in . pdbrc they will only be available from the stack frame from which pdb. set_trace() was called. However, you can add a function globally, so that it will be available in all stack frames, by using an alternative syntax: def cow(): print("I'm a cow") globals()['cow']=cow.
Global variables hold their values throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program. A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration.
Open JS console, write var x = function() {console. log('x')} and then try to call window. x() . In browsers, window is global scope, therefore the function is global.
you need a body (in a cpp
file):
int foo() { return 1; }
and a definition/prototype in a header file, which will be included before any use of the function:
#ifndef MY_FOO_HEADER_ #define MY_FOO_HEADER_ int foo(); #endif
then using it somewhere else:
#include foo.h void do_some_work() { int bar = foo(); }
or use an inline function (doesn't guarantee it'll be inlined, but useful for small functions, like foo
):
#ifndef MY_FOO_HEADER_ #define MY_FOO_HEADER_ inline int foo() { return 1; } #endif
alternatively you can abuse the C-style header based functions (so this goes in a header, the static
forces it to exist in a single compilation unit only, you should avoid this however):
#ifndef MY_FOO_HEADER_ #define MY_FOO_HEADER_ static int foo() { return 1; } #endif
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With