如何在Clion ide中配置CMakeList以使用POSIX pthread函数? [英] How to configure CMakeList in Clion ide for using POSIX pthread functions?
问题描述
我试图在CLIon ide中编译一个简单的POSIX示例,但是我不知道pthread库,我想... 这是代码:
I tried to compile a simple POSIX example in CLIon ide, but it doesn`t know about pthread library, I think... Here is the code:
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函数的第二个参数标记为错误,并给出以下错误:
It is known, that this code is correct, because it's taken from the example in the book. So Clion marks second arguments of pthread_join function as a mistake, giving this error:
error: invalid conversion from ‘void* (*)()’ to ‘void* (*)(void*)’
我想,问题出在CmakeList中.这是我当前的CMakeList:
I suppose, thet the problem is in the CmakeList. Here is my current 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})
推荐答案
您的函数签名对于pthread的回调是错误的.
Your function signature is wrong for the callback to pthread.
func1
和func2
的签名为void* (*)()
.这意味着返回void *并且没有参数
func1
and func2
have the signature void* (*)()
. This means returns a void* and has no parameters
但是pthread需要void* (*)(void*)
在这里,您还有一个void*
作为参数.
But pthread wants void* (*)(void*)
Here you also have a void*
as parameter.
因此您的函数应如下所示:
so your functions should look like this:
void *func1(void* param) ...
您不必使用参数,但必须在声明中使用它.
You don't have to use the parameter but it has to be there in the declaration.
注意:
要告诉cmake链接到pthread,您应该使用以下代码:
To tell cmake to link against pthread you should use this:
find_package( Threads REQUIRED )
add_executable(hello_world ${SOURCE_FILES})
target_link_libraries( hello_world Threads::Threads )
请参阅此处:如何强制cmake包含"-pthread"编译过程中可以选择吗?
这篇关于如何在Clion ide中配置CMakeList以使用POSIX pthread函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!