Home > front end >  Sharing global variable from C library to C main program
Sharing global variable from C library to C main program

Time:11-25

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 functionall_bbox_generated’:
deepstream_app_main.c:98:24: error: ‘mutexundeclared (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: ‘ptrundeclared (first use in this function); did you mean ‘puts’?
     printf("%d ", *(ptr x));

How to share variables between C and C source files?

CodePudding user response:

in a header file... gstdsexamle.h

// disable name mangling in C  
#ifdef __cplusplus
extern "C" {
#endif

// declare your two vars in the header file as extern. 
extern pthread_mutex_t mutex;
extern int *ptr;


#ifdef __cplusplus
}
#endif

in gstdsexamle.c

#include "gstdsexamle.h"

/* only initialise here */
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int *ptr;

in main.c

#include "gstdsexamle.h"

Thats all you need. mutex & ptr are now available in main.cpp/main.c

  • Related