前段时间调试c语言程序时,对一结构体的成员变量进行访问时,编译无法通过,
编译器错误提示为“提领指向不完全类型的指针”。
因程序调用了一些动态链接库,里面使用了不些在动态库中定义的结构,为了了解程序的运行过程,
想知道结构体中的成员变量的值,加上些调试语句,如printf什么的,竟然无法通过编译了。
一开始有点无解,可以通过结构体自身定义的函数进行访问,为什么直接操作的结构体时就出现编译错误,
翻了翻以前的c语言书才知道,对于结构体来说虽然所有的变量默认都是公有的,但是,如果想访问里面的成员变量,
必须有包含对其结构的定义,否则出现如上的错误,c编译器将无法识别结构里面的变量,一般想操作结构体里的成员变量,
都是通过调用结构体中定义的函数接口,来取得结构体中的值,如果想直接访问,在头文件或源文件中加入
结构体的定义就行了。
这种情况出现的可能有(test.h test.c)生成一动态链接库(test.so),使用do.c文件进行测试,如下:
将第10行的“test->value = 20;"注释后,便可通过编译,而且程序可以通过test.h定义的方法来操作成员变量的值。
如果在do.c中加入对Test结构体的描述便可以直接访问成员变量。
编译器错误提示为“提领指向不完全类型的指针”。
因程序调用了一些动态链接库,里面使用了不些在动态库中定义的结构,为了了解程序的运行过程,
想知道结构体中的成员变量的值,加上些调试语句,如printf什么的,竟然无法通过编译了。
一开始有点无解,可以通过结构体自身定义的函数进行访问,为什么直接操作的结构体时就出现编译错误,
翻了翻以前的c语言书才知道,对于结构体来说虽然所有的变量默认都是公有的,但是,如果想访问里面的成员变量,
必须有包含对其结构的定义,否则出现如上的错误,c编译器将无法识别结构里面的变量,一般想操作结构体里的成员变量,
都是通过调用结构体中定义的函数接口,来取得结构体中的值,如果想直接访问,在头文件或源文件中加入
结构体的定义就行了。
这种情况出现的可能有(test.h test.c)生成一动态链接库(test.so),使用do.c文件进行测试,如下:
- //file name : test.h
- typedef struct _Test Test;
- void set_value(Test *test, int value);
- int get_value(Test *test);
- void set(Test *test);
- //file name : test.c
- #include "test.h"
- struct _Test
- {
- int value;
- };
- void set_value(Test *test, int v)
- {
- test->value = v;
- }
- int get_value(Test *test)
- {
- return test->value;
- }
- void set(Test *test)
- {
- test->value = 100;
- }
- //生成动态库test.so
- # gcc -fpic -shared -o test.so test.c test.h
- //file name : do.c
- #include <stdio.h>
- #include <malloc.h>
- #include "test.h"
- int main()
- {
- Test *test = (Test *)malloc(sizeof(Test *));
- test->value = 20;
- printf("%d/n", get_value(test));
- set_value(test, 10);
- printf("%d/n", get_value(test));
- set(test);
- printf("%d/n", get_value(test));
- return 0;
- }
- #gcc do.c ./test.so -o do
- #错误: 提领指向不完全类型的指针 //因为在do.c文件中只包含了test.h对结构的声明,没有实际的定义
如果在do.c中加入对Test结构体的描述便可以直接访问成员变量。
- //file name : do.c
- #include <stdio.h>
- #include <malloc.h>
- #include "test.h"
- struct _Test
- {
- int value;
- };
- int main()
- {
- Test *test = (Test *)malloc(sizeof(Test *));
- test->value = 20;
- printf("%d/n", get_value(test));
- set_value(test, 10);
- printf("%d/n", get_value(test));
- set(test);
- printf("%d/n", get_value(test));
- return 0;
- }
- #gcc do.c ./test.so -o do //通过编译,执行
- #./do //显示正常调用的结果
- #20
- #10
- #100