[C language] An example of structure variable reference

File test_funcs.c:

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

struct t_Test
{
    int n1;
    int n2;
};


struct t_Test *alloc_Test(void)
{
    struct t_Test *pTest=NULL;

    pTest=malloc(sizeof(struct t_Test));
    pTest->n1 = 1;

    return pTest;
}

void func1(struct t_Test *pTest)
{
    printf("%s\n",__FUNCTION__);
    printf("n1:%d\n",pTest->n1);
    return;
}

File test.c:

#include <stdio.h>

extern struct t_Test *alloc_Test(void);
extern void func1(struct t_Test *pTest);
void main(void)
{
    struct t_Test *pTest=NULL;

    pTest=alloc_Test();
    func1(pTest);
    return;

}

Compile:
 

gcc test.c test_funcs.c -o test

run:

./test
func1
n1:1

When the structure struct t_Test is referenced in the file test.c, it does not include the header file that defines struct t_Test.

Interpretation of GPT conversations:

您提供的代码示例非常有趣,分析如下:
1. test_funcs.c中定义了struct t_Test结构体,以及相关的函数alloc_Test()和func1()。
2. test.c中通过extern引用了alloc_Test()和func1(),但没有include test_funcs.c或定义struct t_Test。
3. 这是可以成功编译和运行的,因为C语言有一个特性 - 如果一个结构体只被指针引用,那么编译器不需要其完整定义,只需要声明即可。
4. 所以在test.c中,通过struct t_Test * pTest声明了指针,编译器知道它是一个结构体指针,就可以在外部引用了。
5. 运行时,test.c会链接到test_funcs.c,从而获取struct t_Test的完整定义,以及相关函数的实现。
6. 这利用了C语言对不完整类型(incomplete type)的支持,允许指针在不定义具体类型的情况下进行引用。
7. 但如果test.c想访问结构体成员,或者拷贝传递结构体,就必须include相关头文件,提供完整定义。
综上,通过指针引用,C语言可以不完整声明类型就使用,但具体操作还是需要完整定义。这提供了一定的编译耦合灵活性。

Guess you like

Origin blog.csdn.net/eidolon_foot/article/details/132558454