C语言 —— extern函数(形参为自定义结构体)

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;
}
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值