[英]how do i use vars, functions and structs in other files?
In timer.c
I have 在
timer.c
我有
typedef struct Timer {
int startTicks;
int pausedTicks;
int paused;
int started;
} Timer;
void Init( Timer *t )
{
t->startTicks = 0;
t->pausedTicks = 0;
t->paused = 0;
t->started = 0;
}
What do i need to do in main.c to make use of this struct and functions in that file? 为了在该文件中使用此结构和函数,我需要在main.c中做什么?
In general, .c files contain definitions and .h files contain declarations. 通常,.c文件包含定义,.h文件包含声明。 A better approach would be to keep your definitions in a header:
更好的方法是将定义保留在标题中:
//timer.h
#ifndef TIMER_H //include guard
#define TIMER_H
typedef struct Timer { //struct declaration
int startTicks;
int pausedTicks;
int paused;
int started;
} Timer;
void Init( Timer *t ); //method declaration
#endif
//timer.c
#include "timer.h"
void Init( Timer *t ) //method definition
{
t->startTicks = 0;
t->pausedTicks = 0;
t->paused = 0;
t->started = 0;
}
//main.c
#include "timer.h" //include declarations
int main()
{
Timer* t = malloc(sizeof(Timer));
Init(t);
free(t);
return 0;
}
Learn to use header files (usually named *.h
) and #include
them. 学习使用头文件 (通常名为
*.h
)并#include
它们。
Learn how to compile a program with several compilation units, eg with a Makefile . 了解如何使用多个编译单元(例如Makefile)编译程序。
Don't forget to enable all warnings and debugging information (with GCC, that means gcc -g -Wall
, ie CFLAGS=-g -Wall
in your Makefile
). 不要忘记启用所有警告和调试信息(对于GCC,这意味着
gcc -g -Wall
,即Makefile
CFLAGS=-g -Wall
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.