2016-03-05 40 views
1

我试图用我的线程函数内部的主功能分配的内存,但我得到的错误: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]); 
} 

我该如何解决这个错误?

+1

包含'.c'源文件是不寻常的。 – MikeCAT

+1

您为一个指针分配空间,然后使用其中的三个:(( –

+0

)我应该使用其他方法来包含文件吗? –

回答

4

变量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" 

这是需要避免的foo重复定义时main.ctest1.c都编译。 (假设你用类似于cc main.c test1.c的东西来编译代码)。推荐(尽管可选)也包括test1.htest1.c中。


马丁詹姆斯还提到:

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); 
+0

嘿谢谢!一切正常。 –

3

product_line的定义是无法访问的,因为它是一个局部变量,而不是全局变量。

制作product_line全球是一个简单的方法来解决。

另一种解决方法是通过product_line作为参数。

#include <stdio.h> 
#include <stdlib.h> 
#include <pthread.h> 

void * foo(void *param) 
{ 
    char** product_line = param; 
    int i; 
    printf("%s\n", product_line[0]); 
    for (i = 0; i < 3; i++) 
     printf("%s\n", product_line[i]); 
    return NULL; 
} 

int main(void) 
{ 
    const char** product_line; /* strings literals are not modifyable */ 
    product_line = malloc(sizeof(const char *) * 3); /* Do allocate enough buffer! */ 
    if (product_line == NULL) /* You should check if malloc() was successful. */ 
    { 
     perror("malloc"); 
     return 1; 
    } 
    product_line[0] = "Toy"; 
    product_line[1] = "Chair"; 
    product_line[2] = "Door"; 

    pthread_t thread_tid; 
    pthread_create(&thread_tid, NULL, foo, product_line); 

    pthread_join(thread_tid, NULL); 

    free(product_line); /* You should free() what you allocatted via malloc(). */ 
    return 0; 
} 
1

您应该知道本地(自动)变量和全局变量之间的区别。在下面的链接变量的

范围: http://www.tutorialspoint.com/cprogramming/c_scope_rules.htm

如果你读了前面的教程,你就可以自行检测错误。product_line变量是auto,这意味着一旦你进入“main”函数,它将在堆栈区域中创建,并通过退出而被销毁。

因此,该变量不适用于foo函数;不在它的堆栈上。 建议的解决方法:

  • 做一个全局指针是缴费为您的所有功能

  • 添加新的论据foo功能,该指针传递给它。

注:

这是不常见的包括.c文件,包括.H而不是具有该模块的原型和定义的类型。

+0

@tijko,谢谢你的重新格式化:) –