Reputation: 21589
I am trying to compile a C++ program and it gives me this error.
undefined reference to 'some_function'
Whereas I do add the file which contains some_function
in the makefile. Also I include the declaration of some_function
in the file where I use it. So why does the compiler still complains that it can't find it? What can be the possible reasons?
My makefile is like that
CXX = g++
CXXFILES = dlmalloc.c pthreads.cpp queue.cpp
CXXFLAGS = -O3 -o prog -rdynamic -D_GNU_SOURCE
LIBS = -lpthread -ldl
all:
$(CXX) $(CXXFILES) $(LIBS) $(CXXFLAGS)
clean:
rm -f prog *.o
some_function
is defined in dlmalloc.c
and used inside pthreads.cpp
. Does it have to do with the fact that dlmalloc.c
is a C source code file and others are C++ files. Maybe I should use the extern "C"
keyword with some_function
here, right?
Upvotes: 1
Views: 634
Reputation: 254431
Maybe I should use the extern "C" keyword here, right?
Yes. If you want to call a function compiled as C from C++ code, then you need to declare it extern "C"
- but only in C++, since that's not valid syntax in C.
You can use the __cplusplus
preprocessor symbol to create a header that's valid for either language:
#ifdef __cplusplus
extern "C" {
#endif
void some_function();
/* many, many more C declarations */
#ifdef __cplusplus
}
#endif
The stuff inside extern "C" { ... }
is handled as C declarations. Be careful to make sure each function is always declared this way for C++, and in the odd chance that the C function is actually written in C++ (strongly discouraged!) the decaration must come before the actual definition of the function.
Upvotes: 8