In projectA.vcproj
#ifdef __cplusplus
extern "C" {
#endif
void functionA();
#ifdef __cplusplus
}
#endif
void functionA()
{
//function defined
}
In projectB.vcproj:
void functionB() ;
#include "fileA.h"
#include "fileB.h"
void functionB() {
functionA(); // error: undefined reference to 'functionA'
}
I am getting the error when I compile my code on Linux, please help me fix this.
You have to link the files together.
Source code ---compile--> Object files ---link--> Application fileA.c ------------+ |---> fileA.o ---------+ +---+ | | | fileA.h --------+ +--> a.out | | +---+ | |---> fileB.o ---------+ fileB.cpp ----------+
The "undefined reference to XXX" error message is given by the linker, after successful compilation.
You need to make sure all files are linked together.
$ fileA.c fileA.h fileB.cpp fileB.h $ $ fileA.c fileA.h fileA.o fileB.cpp fileB.h fileB.o $ $ a.out fileA.c fileA.h fileA.o fileB.cpp fileB.h fileB.o
The error message is probably coming from the linker, so you need to ensure you compile both source files and link them properly:
gcc -c fileA.c
g++ -c fileB.cpp
g++ -o program fileB.o fileA.o
You should, of course, ensure that fileA.c
includes fileA.h
. If you omit the header from fileA.c
and if you compile the code using:
g++ -c fileA.c # g++ instead of gcc
g++ -c fileB.cpp
g++ -o program fileB.o fileA.o
Then you will get the missing reference because g++
will have created a C++ linkage functionA()
but will be expecting to call a C linkage functionA()
.
However, you should not compile C code with g++
; that is asking for trouble.
When originally asked, fileB.cpp
didn't include any headers.
#include "fileB.h"
#include "fileA.h" // Provide extern "C" declaration of functionA()
void functionB() {
functionA();
}
You need to include the header file of functionA in functionB's header file. So in fileB.h add the line #include "fileA.h"
How do you compile?
gcc filea.c fileb.cpp
Should do the Trick.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.