-1

I am working on a project that utilizes C source code to call upon a C++ function that is also linked to a C++ library. I have been able to allow for my C code to call on the C++ function, however I also want my C++ function to have access to the global variables defined in the C source code. I currently get errors when linking the C/C++ code .o files. The error messages go through each of the .o files that use these global variables and states "undefined reference to.."

This isn't the exact code or anything but basically a very simple of example of what I am trying to do. The constants.h file also gets used by other C code.

constants.h

#ifdef __cplusplus
extern "C" {
#endif

extern const int x;

#ifdef __cplusplus
}
#end if

constants.c

int x = 5;

mycppcode.cpp

#include "constants.h"

void print_x(int x){

    printf("%d", x);

};
jdhabez
  • 41
  • 4
  • Static or dynamic linkage? – rAndom69 May 15 '19 at 16:53
  • Please show in your question the commands you use to compile and link the code. – Bodo May 15 '19 at 16:54
  • This answer specifically: https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix/12574420#12574420 – πάντα ῥεῖ May 15 '19 at 16:55
  • In the header you've defined `x` as a `const int` and in the source file as a plain `int`. Was that a typo? Also, it's more usual to wrap the `#include` with an `extern "C"` in the cpp sources. – ChrisD May 15 '19 at 16:55
  • The argument `int x` takes precedence over the global variable `int x = 5;` Which is to say that the correctness of your code depends on code that you haven't shown. See [mcve]. – user3386109 May 15 '19 at 16:56
  • @ChrisD yes, it is a typo sorry. I've tried moving the extern "C" to the cpp source as well. – jdhabez May 15 '19 at 16:59

1 Answers1

0

You need to link the .o file where you have that value defined. Compile time, the compiler would not worry about the value. but at link time, compiler is trying to find the value among all the .o and linked libraries. if it cannot find, you will get that error.

Tony
  • 632
  • 1
  • 4
  • 18