-1

I have to modify a C project because I need to use, now, a C++ function.

Let's assume that I have a file called A.c:

A.c

uchar *const x;
uchar *const y;
/.../

and other files that also use these variables, let's call them B.c and C.c:

B.c

extern uchar *const x;
extern uchar *const y;
/.../
foo1(x);
bar1(y);

C.c

extern uchar *const x;
extern uchar *const y;
/.../
foo1(x);
bar1(y);

When I compile all the file with a C compiler everything work perfectly. Now I need to use some C++ function so I need to recompile everything with a C++ compiler. Here the errors:

undefined reference to `::x(void)'
undefined reference to `::y(void)'

Following the advice in the answer here, and using extern "C" around the variable in B.c and C.c generates other errors

Some idea on how to solve this problem?

Leos313
  • 5,152
  • 6
  • 40
  • 69
  • 1
    I think the use of `extern` and the error are unrelated. You don't need to recompile everything with a C++ compiler by the way, typically C++ compilers also compile C and can link C and C++ code together without issues. – nwp Jan 15 '18 at 16:47
  • 3
    Please post a [mcve]. A C++ compiler will not misinterpret your variable declarations as function declarations. – molbdnilo Jan 15 '18 at 17:02
  • @ Sneftel, I had a look at the question you are speaking about but using extern "C" around the variable in B.c and C.c generated other errors – Leos313 Jan 15 '18 at 17:08
  • 1
    Post all the code needed for readers to replicate the problem, not just ellipsised fragments, about which there is no point in speculating. The hopelessly incomplete code you provided shows no evidence that you ever actually instantiate those variables, so there's no reference to be made. But how would we know? – underscore_d Jan 15 '18 at 17:15
  • 1
    I am going to re-write the question including the whole files so I can delete this one – Leos313 Jan 15 '18 at 17:23
  • 1
    You appear to be getting undefined references to two global functions (ones with single letter names — I hope that's an artefact of masking the source when asking on SO). Are you sure these are related to your global variables with similar names? – Jonathan Leffler Jan 15 '18 at 17:39

1 Answers1

0

The extern keyword should be placed in the header file, and the variable definition need only be in one source file, so what you want is this:

In A.h:

extern uchar *const x;
extern uchar *const y;

In A.c

uchar *const x;
uchar *const y;

In B.c

#include "A.h" 

void someFunction() {
    foo(x);
    bar(y);
}

In C.c

#include "A.h"

void someOtherFunction() {
    foo(x);
    bar(y);   
}
Nasser Al-Shawwa
  • 3,573
  • 17
  • 27