By jdhabez


2019-05-15 16:49:53 8 Comments

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);

};

1 comments

@Tony 2019-05-15 16:53:46

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.

@jdhabez 2019-05-15 16:57:19

but I am doing that...

Related Questions

Sponsored Content

13 Answered Questions

[SOLVED] What is the effect of extern "C" in C++?

15 Answered Questions

[SOLVED] How can I profile C++ code running on Linux?

  • 2008-12-17 20:29:24
  • Gabriel Isenberg
  • 471562 View
  • 1664 Score
  • 15 Answer
  • Tags:   c++ unix profiling

1 Answered Questions

[SOLVED] The Definitive C++ Book Guide and List

  • 2008-12-23 05:23:56
  • grepsedawk
  • 2166518 View
  • 4248 Score
  • 1 Answer
  • Tags:   c++ c++-faq

10 Answered Questions

11 Answered Questions

[SOLVED] Global Git ignore

  • 2011-09-07 14:16:11
  • Mild Fuzz
  • 286389 View
  • 760 Score
  • 11 Answer
  • Tags:   git global gitignore

21 Answered Questions

[SOLVED] What is the "-->" operator in C++?

34 Answered Questions

5 Answered Questions

[SOLVED] What is ":-!!" in C code?

4 Answered Questions

5 Answered Questions

[SOLVED] Is there an inline way to mix c and c++ prototypes?

  • 2013-07-01 18:43:08
  • chacham15
  • 475 View
  • 10 Score
  • 5 Answer
  • Tags:   c++ c

Sponsored Content