static static function

a.h

static void fun();

a.cpp




main.cpp

#include "a.h"

int main()
{
    fun();
    return 1;
}

Occurs declared undefined.

error C2129: The static function "void fun(void)" has been declared but not defined [E:lown_projectloutlbuildlown_projectlown_project.vcxproj]

a.h

static void fun();

a.cpp

static void fun()
{

}


main.cpp

#include "a.h"

int main()
{
    fun();
    return 1;
}

Occurs declared undefined.

error C2129: The static function "void fun(void)" has been declared but not defined [E:lown_projectloutlbuildlown_projectlown_project.vcxproj]

a.h

static void fun()
{

}

a.cpp


main.cpp

#include "a.h"

int main()
{
    fun();
    return 1;
}

Compilation passed.

There are header files ah, source files a.cpp, main.cpp. Since static is only visible in the file where it is located. Therefore, the files containing this file are also visible. Therefore, the function is directly defined in ah, and it can be compiled and passed when main.cpp contains ah.

equivalent to

a.h

static void fun()
{

}

a.cpp


main.cpp

#include "a.h"

int main()
{
    fun();
    return 1;
}


///
//将#include "a.h"翻译成

static void fun()
{

}

main.cpp //将变成

static void fun()
{
}

int mian()
{
    fun();
    return 1;
}

 Remark:

ah has a different address each time it is included, so it can be included infinitely without conflicts.

Therefore, using a static function can make the function have the same name.

To sum up: If a function is only used in a certain cpp, and you don't want to expose this function to the outside world, then you should define it as a static function and define it in cpp.

Guess you like

Origin blog.csdn.net/qq_30460949/article/details/127100786