【问题标题】:How to configure CMakeList in Clion ide for using POSIX pthread functions?如何在 Clion ide 中配置 CMakeList 以使用 POSIX pthread 函数?
【发布时间】:2016-10-18 07:06:11
【问题描述】:

我尝试在 CLIon ide 中编译一个简单的 POSIX 示例,但它不知道 pthread 库,我认为... 代码如下:

void *func1()
{
    int i;
    for (i=0;i<10;i++) { printf("Thread 1 is running\n"); sleep(1); }
}
void *func2()
{
    int i;
    for (i=0;i<10;i++) { printf("Thread 2 is running\n"); sleep(1); }
}

int result, status1, status2;
pthread_t thread1, thread2;

int main()
{
    result = pthread_create(&thread1, NULL, func1, NULL);
    result = pthread_create(&thread2, NULL, func2, NULL);
    pthread_join(thread1, &status1);
    pthread_join(thread2, &status2);
    printf("\nПотоки завершены с %d и %d", status1, status2);

    getchar();
    return 0;
}

众所周知,这段代码是正确的,因为它取自书中的示例。所以 Clion 将 pthread_join 函数的第二个参数标记为错误,给出这个错误:

error: invalid conversion from ‘void* (*)()’ to ‘void* (*)(void*)’ 

我想,问题出在 CmakeList 中。这是我当前的 CMakeList:

cmake_minimum_required(VERSION 3.3)
project(hello_world C CXX)



set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -pthread")



set(SOURCE_FILES main.cpp)
add_executable(hello_world ${SOURCE_FILES})

【问题讨论】:

  • 在“已知”之后有“,”而不是“?”

标签: cmake pthreads posix clion


【解决方案1】:

您的函数签名对于 pthread 的回调是错误的。

func1func2 具有签名 void* (*)()。这意味着返回一个 void* 并且没有参数

但是 pthread 想要void* (*)(void*) 这里你也有一个void* 作为参数。

所以你的函数应该是这样的:

void *func1(void* param) ...

您不必使用该参数,但它必须在声明中。

注意:

要告诉 cmake 链接到 pthread 你应该使用这个:

find_package( Threads REQUIRED ) 
add_executable(hello_world ${SOURCE_FILES})
target_link_libraries( hello_world Threads::Threads )

请看这里:How do I force cmake to include "-pthread" option during compilation?

【讨论】:

  • 嗯...问题不在于函数的签名,而在于 pthread_join 中的参数 status1 和 status2。我编辑了我的 CMakeList 为 youve written, but it didnt 效果。
  • 底部注释在稍微不同的情况下帮助了我,所以谢谢!
猜你喜欢
  • 2015-07-25
  • 1970-01-01
  • 2015-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多