C 语言隐藏结构体细节

C 语言隐藏结构体细节

头文件中声明

在头文件的声明结构体的类型和对结构体的操作方法

#ifndef __MY_INCLUDE_H__
#define __MY_INCLUDE_H__
#include <stdio.h>
#include <malloc.h>

struct thread;

char get_thread_flag(struct thread * thread);
char get_thread_flags(struct thread * thread);
char *get_thread_name(struct thread * thread);
void set_thread_name(struct thread * thread, char *name);
struct thread *new_thread(void);

#endif

源程序中定义结构体

源程序中定义结构体的类型以及实现对结构体操作的方法

#include <stdio.h>
#include <string.h>
#include "my_include.h"

struct thread 
{
    char name[10];
    char priority;
    char flags;
};

char get_thread_flag(struct thread * thread)
{
    return (thread->flags);
}

char *get_thread_name(struct thread * thread)
{
    return (thread->name);
}

void set_thread_name(struct thread * thread, char *name)
{
    strcpy(thread->name, name);
}

char get_thread_flags(struct thread * thread)
{
    return (thread->flags);
}

struct thread *new_thread(void)
{
    struct thread *thread = NULL;
    thread = (struct thread *)malloc(sizeof(struct thread));
    if(thread == NULL)
    {
        printf("malloc failed when new thread\n");
    }
    else
    {
        return thread;
    }
}

其它文件获取结构体信息

其它文件不需要知道结构的具体细节,只需要调用提供的操作结构体的方法即可

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

int main(int argc, char *argv[])
{
    printf("hello world\n");
    struct thread *thread;

    thread = new_thread();
    set_thread_name(thread, "main thread");
    printf("thread name is: %s\n", get_thread_name(thread));

    while(1);
    return 0;
}

编译命令

gcc.exe test.c include.c -o test

输出结果

hello world
thread name is: main thread
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值