Search code examples
c++static-functions

How can you access the function from another translation unit without including any files?


I was reading about static functions and it was said that if the function is static then you can use it only in the same file. After testing it, I realized it is not true because if you include the file with a static function you can still use that function in another file. Then I read a clarification that you can actually use static function only in the same translation unit. Ok, that makes sense because it means .cpp + includes, but even if the function is not static, you will still not be able to use it unless you include the file. So how is it even possible to access a function from another translation unit in the first place without including anything, what is the point of static functions?

Main.cpp

#include "Staticf.h"

void main()
{
  visible();
}

Staticf.h

#pragma once
#include <iostream>
using namespace std;

static void visible()
{
  cout << "Static function is visible\n";
}

This compiles alright. If I make that function non-static and remove #include "Staticf.h" I will not be able to use it in Main anyways. So why are static functions needed if you can't access non-static as well?


Solution

  • You can access non-static functions from other translation units. You just need a forward declaration:

    somemodule.cpp

    void func()
    {
      // details
    }
    

    main.cpp

    void func();
    
    int main()
    {
      func();
    }
    

    It is, of course, a best practice to put the forward declaration in a header file.

    So what use are static functions?

    In modern C++, they actually aren't much use. static is a feature C++ inherited from C. In C, declaring a helper function static is actually pretty useful because C doesn't have namespaces. You can use static to eliminate the chance of name collisions between your private helper functions and the private helper functions in other translation units. In C++, it's generally preferred to wrap your private helpers in a class or anonymous namespace.