Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you define a global function in C++?

Tags:

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?

like image 329
Cory Klein Avatar asked Jul 29 '11 14:07

Cory Klein


People also ask

What is a global function in C?

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.

How do you define a global function?

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.

When and how do you define a global in C?

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.

How do you write a global function?

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.


1 Answers

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 
like image 102
Necrolis Avatar answered Sep 19 '22 23:09

Necrolis