1.0 包含头文件(结构体,函数声明);定义相同结构的struct
// test.c
#include <stdio.h>
#include <stdlib.h>
#include "test.h"
void show_struct(HASH_S* pHash)
{
printf("This is show_struct!\n");
printf("key = %d, val = %d\n", pHash->key, pHash->val);
}
// test.h
typedef struct {
int key;
int val;
} HASH_S;
void show_struct(HASH_S* pHash);
// main.c
#include <stdio.h>
#include <stdlib.h>
#include "test.h"
typedef struct {
int key;
int val;
} HASH_STR; // 已包含test.h,HASH_S结构体存在,只可另命名否则会error
int main()
{
HASH_STR h = {5, 500};
// ① warning:passing argument 1 of 'show_struct' from incompatible pointer type [-Wincompatible-pointer-types]
// show_struct(&h);
show_struct((void*)&h); // ② 强转为void*,不会warning
printf("This is main.c!\n");
return 0;
}
2.0 不包含头文件,使用extern,再定义同名结构体
// test.c
#include <stdio.h>
#include <stdlib.h>
#include "test.h"
void show_struct(HASH_S* pHash)
{
printf("This is show_struct!\n");
printf("key = %d, val = %d\n", pHash->key, pHash->val);
}
// test.h
typedef struct {
int key;
int val;
} HASH_S;
void show_struct(HASH_S* pHash);
// main.c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int key;
int val;
} HASH_S; // 未包含test.h,此处再定义HASH_S结构体不会warning或error
extern void show_struct(HASH_S* pHash);
int main()
{
HASH_S h = {5, 500};
show_struct(&h);
printf("This is main.c!\n");
return 0;
}
2.1 不包含头文件,使用extern,再定义不同名结构体
vscode提示:找不到“show_struct”的函数定义。
编译并不会warning或error。
这是为什么?
// test.c
#include <stdio.h>
#include <stdlib.h>
#include "test.h"
void show_struct(HASH_S* pHash)
{
printf("This is show_struct!\n");
printf("key = %d, val = %d\n", pHash->key, pHash->val);
}
// test.h
typedef struct {
int key;
int val;
} HASH_S;
void show_struct(HASH_S* pHash);
// main.c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int key;
int val;
} HASH_STR;
extern void show_struct(HASH_STR* pHash); // vscode提示:找不到“show_struct”的函数定义。
// 编译并不会warning或error
int main()
{
HASH_STR h = {6, 500};
show_struct(&h);
printf("This is main.c!\n");
return 0;
}