How do I exchange variables between C and C ++ code?

I am working on a C ++ project that implements C code and I am stuck on a segmentation fault. Segfault occurs when I try to access a global C variable in my C ++ code.

Code overview:
I have one c file called video_stage.c with the following piece of code:

#include "video_stage.h"

uint8_t*  pixbuf_data = NULL;    //pointer to video buffer
vp_os_mutex_t  video_update_lock = PTHREAD_MUTEX_INITIALIZER;  

C_RESULT output_gtk_stage_transform( void *cfg, vp_api_io_data_t *in, vp_api_io_data_t *out)

   /* Get a reference to the last decoded picture */
   pixbuf_data      = (uint8_t*)in->buffers[0];

   return (SUCCESS);


This function is called periodically by other C code and updates the pixbuf_data pointer points to point to the RGB video clip.

Video_stage.h header file:


#ifdef __cplusplus
extern "C" {

#include <config.h>
#include <VP_Api/vp_api_thread_helper.h>
#include <VP_Api/vp_api.h>                  //hier zit vp_os_mutex in geinclude

PROTO_THREAD_ROUTINE(video_stage, data);

#ifdef __cplusplus

extern uint8_t*  pixbuf_data;
extern vp_os_mutex_t  video_update_lock;

#endif // _IHM_STAGES_O_GTK_H


The header file contains the extern declaration of the pixbuf_data pointer.

And here is the cpp file:

#include <iostream>
#include "video_stage.h"

int ardrone_update(ardrone_t *d)
    uint8_t x;

    x = pixbuf_data[0];            //no problem here, this is executed
    std::cout << 5 << std::endl;   //this is executed too
    std::cout << x << std::endl;   //segfault occures here



When a function in the cpp file is called (by different cpp code), a segfault occurs on the cout command that prints x.

When I do a printf of the first buffer element in file c, I get what I expect.

I'm sure it has something to do with mixing c and c ++ code, but according to my research I did stuff to make c and c ++ code compatible.


source to share

3 answers

In C ++, code pixbuf_data

defined in a C source must be declared using the C linkage:

extern "C" uint8_t*  pixbuf_data;


Without, extern "C"

C ++ code should not be referenced unless there is another (duplicated) definition pixbuf_data

with a C ++ reference.



grab yourself a debugger and run your program under that. The trace code doesn't tell you at all where the segfault occurs, IO is slower.

In the code you're showing us, you don't seem to allocate memory for pixbuf_data

. Anything can happen when you access it without assigning a valid pointer to it.



I am trying to use a variable between a C project and a C ++ project. but when I build my solution I got "error LNK2001: unresolved external symbol" struct configuration g_conf ". This is what I did:

==== In project C ==

I create a header file and on it I create my structure

typedef struct{ int maxUser; }Configuration;
extern Configuration conf;


==== In a C ++ project =======

In the main file:

#include "../ProjectC/header.h"

int main(){ conf.maxUser = 10; }




All Articles