Why do I get "undefined reference to..." when trying to call a C-function inside a .cpp-file?
-
I am writing code for an ARM processor and compiling with GCC inside Eclipse IDE. My project has 3 files, main.c, myDummyFile.h and myDummyFile.cpp. myDummyFile.h:
#ifndef MYDUMMYFILE_H_
#define MYDUMMYFILE_H_#ifdef __cplusplus
extern "C" {
#endifint myDummyFunction();
#ifdef __cplusplus
} //end extern "C"
#endif#endif /* MYDUMMYFILE_H_ */
myDummyFile.cpp:
#include using namespace std;
// Throw in some C++ syntax to make sure this file is compiled as a C++ file and not as C-file
using cPlusPlusCallback_t = function ;volatile int preventOptimizationDummy = 0;
int myDummyFunction() {
return preventOptimizationDummy++;
}main.c:
#include
#include
#include "myDummyFile.h"int main(int argc, char* argv[]) {
return myDummyFunction();
}Does anybody know why I get the error message "undefined reference to `myDummyFunction'" when I try to compile this? If I remove the call to myDummyFunction() then it compiles fine so the compiler does seem to be able to compile .cpp-files.
-
I am writing code for an ARM processor and compiling with GCC inside Eclipse IDE. My project has 3 files, main.c, myDummyFile.h and myDummyFile.cpp. myDummyFile.h:
#ifndef MYDUMMYFILE_H_
#define MYDUMMYFILE_H_#ifdef __cplusplus
extern "C" {
#endifint myDummyFunction();
#ifdef __cplusplus
} //end extern "C"
#endif#endif /* MYDUMMYFILE_H_ */
myDummyFile.cpp:
#include using namespace std;
// Throw in some C++ syntax to make sure this file is compiled as a C++ file and not as C-file
using cPlusPlusCallback_t = function ;volatile int preventOptimizationDummy = 0;
int myDummyFunction() {
return preventOptimizationDummy++;
}main.c:
#include
#include
#include "myDummyFile.h"int main(int argc, char* argv[]) {
return myDummyFunction();
}Does anybody know why I get the error message "undefined reference to `myDummyFunction'" when I try to compile this? If I remove the call to myDummyFunction() then it compiles fine so the compiler does seem to be able to compile .cpp-files.
You need to add the following line to myDummyFile.cpp:
#include "myDummyFile.h"
Otherwise the compiler will generate a decorated* name for
myDummyFunction
, because the source file is C++ not C. *In C++ external names have additional characters so the linker will not match what is called from your main file.