0

I have relatively simple setup.

I have a new Console C++ project.

But I was playing with global vars in C, and added two new .c files like this.

// Fruit.h
extern int global_variable;

Now the source:

// Fruit.c
#include "Fruit.h"
#include <stdio.h>

int global_variable = 37;

Also,

// Orange.h
void use_it(void);

and

// Orange.c
#include "Orange.h"
#include "Fruit.h"
#include <stdio.h>

void use_it(void)
{
    printf("Global variable: %d\n", global_variable++);
}

Finally, this is my main:

#include "stdafx.h"
#include "Orange.h"
#include "Fruit.h"

int _tmain(int argc, _TCHAR* argv[])
{
    use_it();

    return 0;
}

But this is the error I get: "error LNK2019: unresolved external symbol "void __cdecl use_it(void)" (?use_it@@YAXXZ) referenced in function _wmain"

Any help?

followed this advice on global vars: here

Community
  • 1
  • 1
  • C and C++ are two different languages. If you do intend to actually use both in your project, you have not done enough. If you intend to use only one of them, make sure you know which one. – n. m. could be an AI Dec 11 '13 at 14:39
  • 1
    Duplicate of [What is an undefined reference/unresolved external symbol error and how do I fix it?: Symbols were defined in a C program and used in C++ code](http://stackoverflow.com/a/12574420/902497) – Raymond Chen Dec 11 '13 at 14:51

1 Answers1

2

Your main file is a C++ file and the external file is C, if you want to reference a C function from C++ in the header should surround the declarations with

#ifdef __cplusplus
extern "C"{
#endif

// declarations here

#ifdef __cplusplus
}
#endif

or

preface them with extern "C" if those declarations will never be seen from a C file, as C has no idea what extern "C" means.

The issue is that the compiler is looking for a C++ name mangled function not a C function, which uses a different mangling (usually none).

Mgetz
  • 5,108
  • 2
  • 33
  • 51
  • The problem is the [name mangling](http://en.wikipedia.org/wiki/Name_mangling) done in C++. – Max Truxa Dec 11 '13 at 14:37
  • 1
    @MaxTruxa answer updated to incorporate that – Mgetz Dec 11 '13 at 14:39
  • @Mgetz: I typed this: "extern "C" { void use_it(void); }" -- in Orange.h but get a compilation error now –  Dec 11 '13 at 14:40
  • @user2568508 in your case you will need the `#ifdef` guards as C has no idea what `extern "C"` means – Mgetz Dec 11 '13 at 14:41
  • Use `#ifdef __cplusplus` around the `extern "C" {` and `}`. @Mgetz You were faster again :p – Max Truxa Dec 11 '13 at 14:41
  • Seems to work now and indeed the global var seems to be synchronized across different source files. Thanks for the tip I will look more into this solution and why it works –  Dec 11 '13 at 14:43