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