c++ - 未定义对 'some_function' 的引用?

标签 c++ c linux gcc x86-64

我正在尝试编译 C++ 程序,但出现此错误。

undefined reference to 'some_function'

而我确实在 makefile 中添加了包含 some_function 的文件。此外,我在使用它的文件中包含了 some_function 的声明。那么为什么编译器仍然提示找不到呢?可能的原因是什么?

我的makefile就是这样

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_functiondlmalloc.c 中定义并在 pthreads.cpp 中使用。是不是和dlmalloc.c是C源代码文件,其他是C++文件有关。也许我应该在这里使用 extern "C" 关键字和 some_function,对吗?

最佳答案

Maybe I should use the extern "C" keyword here, right?

是的。如果您想从 C++ 代码调用编译为 C 的函数,则需要声明它 extern "C" - 但仅限于 C++,因为这在 C 中不是有效语法。

您可以使用 __cplusplus 预处理器符号来创建对任一语言都有效的 header :

#ifdef __cplusplus
extern "C" {
#endif
void some_function();

/* many, many more C declarations */

#ifdef __cplusplus
}
#endif

extern "C"{ ... } 中的内容作为 C 声明处理。小心确保每个函数总是以这种方式为 C++ 声明,并且 C 函数实际上是用 C++ 编写的(强烈不鼓励!)声明必须在函数的实际定义之前。

关于c++ - 未定义对 'some_function' 的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11316065/

相关文章:

c++ - 如何在模板类中使用友元运算符?

c - 声明数组但不物理分配它

linux - forkIO/killThread 与 forkProcess 的交互

linux - sudo dpkg -i mod-pagespeed-*.deb 给出 "not a debian format archive"错误

c++ - 将 shared_ptr 作为函数的参数

c# - 使用 CSExeCOMServer 如何在 VS C++ 中接收事件

c - 将 C 程序安装到另一台机器上,无需共享代码

c++ - Linux 有没有办法使用 C/C++ 永久设置 IP 地址?

linux - 如何在 vim 的 ex 模式下从缓冲区粘贴?

c++ - Visual Studio 2015 和 opencv 3.0