Static in c – hide that function

In the c language there is no such thing as a class, private/public setup as such, but if you have a allot of c files that may have allot of the same function names inside e.g. swap(void *data, void *data2). So how do you just want to call your swap function and not another one from another c file. Which in this setup it is similar to private method within a class.

So instead of having access to the private keyword, you can define a function to be a static function as below in this header file that I have called static_test.h

#include <iostream>
using namespace std;
static void PrivateAccessable(char *sting);
void PublicAccessable(char *st);
#endif // STATIC_TEST_H

the PublicAccessable function is what is *exposed* to other parts of the main program but the static void PrivateAccesable is not.

So if you try and access it via the int main function like so

#include <iostream>
#include "static_test.h"
int main(int argc, char *argv[])
    PublicAccessable("hi there");
    // undefined reference to `PrivateAccessable(char*)'
    PrivateAccessable("should not be able to access this!!");
    return 0;

The compiler will complain with something similar to the error above the PrivateAccessable line, or

undefined reference to `PrivateAccessable(char*)'

because the linker does not know where that function is, since it is “hidden” within the static_test namespace as such.

Just to complete the code example here is the static_test.c

#include "static_test.h"
static void PrivateAccessable(char *sting)
    cout << sting << endl;
void PublicAccessable(char *st)

Leave a Reply

Your email address will not be published. Required fields are marked *