分享

关于编译错误--提领指向不完全类型的指针

 北漂之邬 2014-02-20
       前段时间调试c语言程序时,对一结构体的成员变量进行访问时,编译无法通过,
编译器错误提示为“提领指向不完全类型的指针”。

      因程序调用了一些动态链接库,里面使用了不些在动态库中定义的结构,为了了解程序的运行过程,
想知道结构体中的成员变量的值,加上些调试语句,如printf什么的,竟然无法通过编译了。

     一开始有点无解,可以通过结构体自身定义的函数进行访问,为什么直接操作的结构体时就出现编译错误,
翻了翻以前的c语言书才知道,对于结构体来说虽然所有的变量默认都是公有的,但是,如果想访问里面的成员变量,
必须有包含对其结构的定义,否则出现如上的错误,c编译器将无法识别结构里面的变量,一般想操作结构体里的成员变量,
都是通过调用结构体中定义的函数接口,来取得结构体中的值,如果想直接访问,在头文件或源文件中加入
结构体的定义就行了。

这种情况出现的可能有(test.h test.c)生成一动态链接库(test.so),使用do.c文件进行测试,如下:
  1. //file name : test.h
  2. typedef struct _Test Test;
  3. void set_value(Test *test, int value);
  4. int  get_value(Test *test);
  5. void set(Test *test);
  1. //file name : test.c
  2. #include "test.h"
  3. struct _Test 
  4. {
  5.     int value;
  6. };
  7. void set_value(Test *test, int v)
  8. {
  9.     test->value = v;
  10. }
  11. int get_value(Test *test)
  12. {
  13.     return test->value;
  14. }
  15. void set(Test *test)
  16. {
  17.     test->value = 100;
  18. }
  1. //生成动态库test.so
  2. # gcc -fpic -shared -o test.so test.c test.h
  1. //file name : do.c
  2. #include <stdio.h>
  3. #include <malloc.h>
  4. #include "test.h"
  5. int main()
  6. {
  7.     Test *test = (Test *)malloc(sizeof(Test *));
  8.     test->value = 20;
  9.     printf("%d/n", get_value(test));
  10.     set_value(test, 10);
  11.     printf("%d/n", get_value(test));
  12.     set(test);
  13.     printf("%d/n", get_value(test));
  14.     return 0;
  15. }
  1. #gcc do.c ./test.so -o do
  2. #错误: 提领指向不完全类型的指针  //因为在do.c文件中只包含了test.h对结构的声明,没有实际的定义
将第10行的“test->value = 20;"注释后,便可通过编译,而且程序可以通过test.h定义的方法来操作成员变量的值。
如果在do.c中加入对Test结构体的描述便可以直接访问成员变量。
  1. //file name : do.c
  2. #include <stdio.h>
  3. #include <malloc.h>
  4. #include "test.h"
  5. struct _Test
  6. {
  7.     int value;
  8. };
  9. int main()
  10. {
  11.     Test *test = (Test *)malloc(sizeof(Test *));
  12.     test->value = 20;
  13.     printf("%d/n", get_value(test));
  14.     set_value(test, 10);
  15.     printf("%d/n", get_value(test));
  16.     set(test);
  17.     printf("%d/n", get_value(test));
  18.     return 0;
  19. }
  1. #gcc do.c ./test.so -o do   //通过编译,执行
  2. #./do                                 //显示正常调用的结果
  3. #20
  4. #10
  5. #100



    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多