I have this code:
// my.h
#ifndef MY_HEADER
#define MY_HEADER
int create_uid();
#endif
// my.cpp
#include "my.h"
static int _next_uid = 0;
int create_uid()
{
return _next_uid++;
}
I want to inline create_uid(), while keeping the _next_uid variable global to the program so the variable is unique.
My questions are:
- Can I do this?
- Is the
inlinestatement require_next_uidto be visible outside the compilation unit?
Note: This doesn't seems to answer those questions clearly.
Summary:
It doesn't work if you put implementation of
inline next_id()to a singlecfile, which means the function is in a single compile unit. Somaincannot findinline next_id(), you'll get the errorundefined reference.It can be compiled if you declare
inline next_id()in a shared header file, in which case each compile unit will properly findinline next_id().In my case, only one instance of this global variable will appear in virtual address space
.DATAsegment of the process. The output number is continuous.Example:
Makefile 8:
main.cpp 12:
second.hpp 1:
second.cpp 7:
share.hpp 4:
share.cpp 7:
Result output:
But if it is changed to:
share.cpp 4:
If changed to
share.hpp 7:
Works
EDIT:
It seems to be an undefined behavior
I'm using `gcc version 11.2.0 (Ubuntu 11.2.0-19ubuntu1)
IN MY CASE
You will have copies of
static int _next_idbut only in the object file. In memory there is only one.main.s 143:
Here function
_Z7next_idvonly appears in memory for 1 time.main.s 147:
The label of
_next_idis_ZL8_next_id, only appears in memory for 1 time as well.