Consider a library that uses stdatomic.h
header. This one will not compile in C++ project, especially if it is required to use structure with atomic components.
How to properly implement library with atomic components, to build with C or C++ compiler? Small demo that builds well - but it seems very shady and holds potential undefined behavior.
lib.h header file
#ifndef LIB_HDR_H
#define LIB_HDR_H
#include <stdint.h>
#include <stddef.h>
#if defined(__cplusplus)
/* C++ atomic header */
#include <atomic>
#define lib_size_t std::atomic<size_t>
#else
/* STDATOMIC C header */
#include <stdatomic.h>
typedef atomic_size_t lib_size_t;
#endif
#if defined(__cplusplus)
extern "C" {
#endif /* defined(__cplusplus) */
/* Tricky part here... */
typedef struct {
lib_size_t a;
lib_size_t b;
} lib_t;
void lib_init(lib_t *l);
#if defined(__cplusplus)
}
#endif /* defined(__cplusplus) */
#endif /* LIB_HDR_H */
lib.c implementation file
#include "lib.h"
/* Not much to do here right now... */
void lib_init(lib_t* l) {
/* These operations shall be atomic */
l->a = 5;
l->b = 10;
}
C++ application file that uses the library
#include <iostream>
#include "lib.h"
lib_t my_lib;
int main() {
lib_init(&my_lib);
}