static variables in an inlined function

2019-01-05 08:56发布

I have a function that is declared and defined in a header file. This is a problem all by itself. When that function is not inlined, every translation unit that uses that header gets a copy of the function, and when they are linked together there are duplicated. I "fixed" that by making the function inline, but I'm afraid that this is a fragile solution because as far as I know, the compiler doesn't guarantee inlining, even when you specify the "inline" keyword. If this is not true, please correct me.

Anyways, the real question is, what happens to static variables inside this function? How many copies do I end up with?

9条回答
狗以群分
2楼-- · 2019-01-05 09:33

Besides any design issues this all may imply, since you're already stuck with it, you should use static in this case not inline. That way everyone shares the same variables. (Static function)

查看更多
We Are One
3楼-- · 2019-01-05 09:40

Inlining means that executable code (instructions) is inlined into the calling function's code. The compiler can choose to do that regardless of whether you've asked it to. That has no effect on the variables (data) declared in the function.

查看更多
劫难
4楼-- · 2019-01-05 09:44

Since I wrote the question I tried it out with Visual Studio 2008. I tried to turn on all the options that make VS act in compliance with standards, but it's possible that I missed some. These are the results:

When the function is merely "inline", there is only one copy of the static variable.

When the function is "static inline", there are as many copies as there are translation units.

The real question is now whether things are supposed to be this way, or if this is an ideosyncracy of the Microsoft C++ compiler.

查看更多
登录 后发表回答