今天打算在main.cpp中加一段C代码,目的是开一个线程来测试一些接口。But,不是不知道,一试吓一跳,一段在用gcc编译通过的代码移植到main.cpp中去,却编译报错了。main.cpp是用g++编译的。于是在各种地方搜索,最后问题得以解决,记录之。
C++中不能像C那样例如:
int *a;
char *b;
a = b; //correct in gcc, but error in g++
a = (int *)b; //correct in gcc, but error in g++
a = static_cast<int *>(b); //correct in g++, cast char* b to int*
所以在强转的时候要注意了。
另外在使用pthread的时候,pthread_create的用法和回调函数的定义形式应该如下:
Source file: test.c
#include <stdio.h>
#include <pthread.h>
#include <stdlib.>
#include <unistd.h>
typedef struct student { //目的是可以传入多个参数给子线程
int id;
char name[16];
} student;
void* function(void* argument); //回调函数必须是 void* f(void* a)形式
void* function(void* argument) //定义
{
#ifdef __cplusplus
student *tmp = static_cast<student *>(argument);
#else
student *tmp = argument;
#endif
printf("id is [%d], name is [%s]\n", tmp->id, tmp->name);
fflush(stdout);
exit(0);
}
int main() {
pthread_t pid;
student a = { 18, "zhangsan\0"};
pthread_create(&pid, NULL, &function, &a); //第三个参数的写法为&f形式,并且f为" void* f(void* a) "
sleep(2); //主线程阻塞2s以等待子线程完成printf打印完成
return 0;
}
Compile command:
$ gcc -g -Wall test.c
Output:
$ ./a.exe
id is [18], name is [zhangsan]
从以上代码可以看出,C代码中的pthread相关代码用g++来编译时,会遇到不少关于指针转换的问题,就是因为C++中不允许隐式转换(implicitly cast)。
而上述代码原型适应在C++代码中加入C代码的创建线程,并且传入多个参数(因为传入结构体,那么结构体中可包含很多参数)。
而用gcc的情况下使用pthread就简单多了。