我试图在线程函数中使用我在主函数中分配的内存,但出现错误:undefined reference to 'product_line'
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "test1.c"
int main()
{
char** product_line;
product_line = malloc(sizeof(char *));
product_line[0] = "Toy";
product_line[1] = "Chair";
product_line[2] = "Door";
pthread_t thread_tid;
pthread_create(&thread_tid, NULL, foo, NULL);
pthread_join(thread_tid, NULL);
return 0;
}
这是线程调用的独立源:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
extern char** product_line;
void * foo(void *param)
{
int i;
printf("%s\n", product_line[0]);
for (i = 0; i < 3; i++)
printf("%s\n", product_line[i]);
}
我该如何修复这个错误?
最佳答案
变量product_line
应该在main
之外声明,否则其他翻译单元无法访问它:
/* main.c */
…
char **product_line;
int main()
{
…
}
MikeCAT 提到的另一个问题:
Including
.c
source file is unusual.
考虑添加头文件test1.h
:
/* test1.h */
#ifndef TEST1_H
#define TEST1_H
void * foo(void *param);
#endif
然后,将 main.c
中的 #include "test1.c"
替换为:
#include "test1.h"
当 main.c
和 test1.c
都被编译时,这是为了避免 foo
的重复定义。 (假设您正在使用类似于 cc main.c test1.c
的东西编译代码。)建议(尽管是可选的)在 中也包含
.test1.h
>test1.c
Martin James 还提到:
You allocate space for one pointer, then use three of them:((
这一行
product_line = malloc(sizeof(char *));
为单个 char *
指针分配空间。但是,您实际上使用了其中的 3 个,因此您需要分配 3 个 char *
指针:
product_line = malloc(sizeof(char *) * 3);
关于c - 如何在线程中共享内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35812048/