C++将函数指针作为参数传递

C++ passing function pointers as arguments

本文关键字:参数传递 指针 函数 C++      更新时间:2023-10-16

我正在尝试传递函数指针,但不断收到编译器错误。我通常不传递函数指针,但这种情况需要它。我认为你只需要看到声明就知道我做错了什么。

在头文件中,我有:

pthread_t * createThread(void *(*func)(void *), string arg)

在实现中是相同的:

pthread_t * createThread(void *(*func)(void *), string arg)

在调用这个函数时,我正在做:createThread(&afunction, "ran Again")

函数的声明是:

void *afunction(void *ptr) //(no header, same for both declaration and implementation).

但是编译器吐出了这个:

    Undefined symbols for architecture x86_64:
  "createThread(void* (*)(void*), std::basic_string<char, std::char_traits<char>, std::allocator<char> >)", referenced from:
      spawnSingleThreadTest()     in threadTests.o

您没有将实现链接到可执行文件。这与函数指针无关。这就是你编译源代码的方式。

相关文章: