Skip to content

Commit

Permalink
Compute cJSON_Version at compile time
Browse files Browse the repository at this point in the history
As CJSON_VERSION_... macros are known to be constant integers, it is
possible to use C macros to transform them to literal strings and to
directly use the result in function cJSON_Version.

As a side-effect, this makes cJSON_Version thread-safe, as a there is no
longer a shared buffer (static char version[15]) shared between threads.
  • Loading branch information
niooss-ledger committed May 14, 2024
1 parent 3249730 commit d34dda6
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions cJSON.c
Original file line number Diff line number Diff line change
Expand Up @@ -121,12 +121,13 @@ CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item)
#error cJSON.h and cJSON.c have different versions. Make sure that both have the same.
#endif

#define STRINGIFY_(s) #s
#define STRINGIFY(s) STRINGIFY_(s)

CJSON_PUBLIC(const char*) cJSON_Version(void)
{
static char version[15];
sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH);

return version;
return STRINGIFY(CJSON_VERSION_MAJOR) "." STRINGIFY(CJSON_VERSION_MINOR) "." \
STRINGIFY(CJSON_VERSION_PATCH);
}

/* Case insensitive string comparison, doesn't consider two NULL pointers equal though */
Expand Down

0 comments on commit d34dda6

Please sign in to comment.