当前位置:网站首页>Scope of inline symbol

Scope of inline symbol

2022-07-05 05:34:00 Raise items

Compile time , Declare as inline The symbol of is expanded at the call , Reduce runtime overhead , At the same time, increase the size of the executable .
This article is about inline The symbol of Scope .

Example 1

a.cpp

#include <iostream>

inline int f()
{
    
	return 10;
}

inline int g = 100;

void fa()
{
    
	int a = f();
	std::cout << a << std::endl;
	std::cout << g << std::endl;
}

b.cpp

#include <iostream>

int f();
extern int g;

void fa();

void fb()
{
    
	int b = f();
	std::cout << b << std::endl;
	std::cout << g << std::endl;
}

int main()
{
    
	fa();
	fb();

	return 0;
}

Running results :
 Insert picture description here
Look like extern Scoped

Example 2

a.cpp unchanged

#include <iostream>

inline int f()
{
    
	return 10;
}

inline int g = 100;

void fa()
{
    
	int a = f();
	std::cout << a << std::endl;
	std::cout << g << std::endl;
}

b.cpp Define the same name inline Symbol

#include <iostream>

inline int f()
{
    
	return 20;
}

inline int g = 200;

void fa();

void fb()
{
    
	int b = f();
	std::cout << b << std::endl;
	std::cout << g << std::endl;
}

int main()
{
    
	fa();
	fb();

	return 0;
}

Running results :
 Insert picture description here
If it's normal extern Symbol , It should be reported redefinition Of link error , And there's no one here . In the whole project, only 1 individual f and 1 individual g, but f and g The value of is equal to Link order of . The latter link is ignored by the first link .

Example 3

a.cpp The symbol in is declared as static

#include <iostream>

static inline int f()
{
    
	return 10;
}

static inline int g = 100;

void fa()
{
    
	int a = f();
	std::cout << a << std::endl;
	std::cout << g << std::endl;
}

b.cpp unchanged

#include <iostream>

inline int f()
{
    
	return 20;
}

inline int g = 200;

void fa();

void fb()
{
    
	int b = f();
	std::cout << b << std::endl;
	std::cout << g << std::endl;
}

int main()
{
    
	fa();
	fb();

	return 0;
}

Running results :
 Insert picture description here
It is recognized in the project 2 individual f and 2 individual g, One is extern Scoped , One is static Scoped .

Conclusion

inline The symbolic scope of the modifier is extern Of , But different from ordinary extern Symbol . In a project It is allowed to define multiple identical inline Symbol , Although it can be compiled , But after the link , Every inline Symbol Only one value will be retained .

So in a project ,inline Embellishment symbols should only ( Think of it as an ordinary extern Symbol ), Avoid quotation confusion .

原网站

版权声明
本文为[Raise items]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140621236511.html