Reputation: 2422
I've tried to cast to void*
and use %p
. I've also tried intptr_t
with a format of %lx
. Both times I get the "Invalid Cast" error.
I'm using -Wall -Werror
which checks that the arguments of the printf()
match the function's format string. So I can't merely count on get_id()
leaving a 4- or 8-byte value on the stack and simply printing that value as hex.
I'm using gcc version 9.2.1 20190827 (Red Hat 9.2.1-1) (GCC)
The OS is Fedora release 31 (Thirty One) . The CPU is 64-bit Intel x86.
Upvotes: 5
Views: 11192
Reputation: 11
I was able to use this work-around in a logging function that had similar requirments:
static std::ostringstream id;
static std::string sid = id.str();
if (sid.empty())
{
id << std::this_thread::get_id();
sid = id.str();
}
// our code actually has a vsnprintf()
printf("[%u:%s] %s", getpid(),
sid.c_str(), another_string );
Same mechanism as answer 1. The thread id type is quite opaque.
Upvotes: 1
Reputation: 20938
Use streams:
std::ostringstream oss;
oss << std::this_thread::get_id() << std::endl;
printf("%s\n", oss.str().c_str());
Upvotes: 9