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

40 Answered Questions

10 Answered Questions

19 Answered Questions

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

  • 2008-12-17 20:29:24
  • Gabriel Isenberg
  • 523493 View
  • 1816 Score
  • 19 Answer
  • Tags:   c++ linux profiling

12 Answered Questions

[SOLVED] Global Git ignore

  • 2011-09-07 14:16:11
  • Mild Fuzz
  • 327331 View
  • 841 Score
  • 12 Answer
  • Tags:   git global gitignore

22 Answered Questions

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

27 Answered Questions

[SOLVED] Easiest way to convert int to string in C++

1 Answered Questions

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

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

15 Answered Questions

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

5 Answered Questions

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

5 Answered Questions

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

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

Sponsored Content