I have gstdsexample.so, a C++ library.
Inside, it has two global variables that I'd like to share between the library and the main C program.
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int *ptr;
Test two scenarios.
Scenario 1
sharedata.h
#ifndef __SHARE_DATA_H__
#define __SHARE_DATA_H__
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int *ptr;
#endif /* __SHARE_DATA_H__ */
Include sharedata.h in gstdsexample.cpp and main.c.
Compilation OK but I get a segmentation fault when gstdsexample.cpp writes data to *ptr.
Scenario 2
Declare two variables in
gstdsexamle.cpp
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int *ptr;
Then declare as extern in main.c.
extern pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
extern int *ptr;
Now I have undefined reference errors to the two variables when compiling main.c.
Scenario 3:
#ifndef __SHARE_DATA_H__
#define __SHARE_DATA_H__
#include <stdio.h>
#include <pthread.h>
extern "C" {
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int *ptr;
}
#endif /* __SHARE_DATA_H__ */
Then include sharedata.h in gstdsexample.cpp and main.c.
Compiling for cpp lib is fine.
But compiling for main.c has errors as
error: expected identifier or ‘(’ before string constant
extern "C" {
^~~
deepstream_app_main.c: In function ‘all_bbox_generated’:
deepstream_app_main.c:98:24: error: ‘mutex’ undeclared (first use in this function); did you mean ‘GMutex’?
pthread_mutex_lock( &mutex );
^~~~~
GMutex
deepstream_app_main.c:98:24: note: each undeclared identifier is reported only once for each function it appears in
deepstream_app_main.c:101:21: error: ‘ptr’ undeclared (first use in this function); did you mean ‘puts’?
printf("%d ", *(ptr+x));
How to share variables between C++ and C source files?
extern "C" { ... }blocks if you want to share them with C code.#ifdef __cplusplus extern "C" { pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int *ptr; } #endif /* __SHARE_DATA_H__ */I did like that but still same error