我有一些 C 代码,我想将其拆分为头文件和源文件:
#ifndef BENCHMARK_H
#define BENCHMARK_H
#ifdef WIN32
#include <windows.h>
double get_time()
{
LARGE_INTEGER t, f;
QueryPerformanceCounter(&t);
QueryPerformanceFrequency(&f);
return (double)t.QuadPart/(double)f.QuadPart;
}
#else
#include <sys/time.h>
#include <sys/resource.h>
double get_time()
{
struct timeval t;
struct timezone tzp;
gettimeofday(&t, &tzp);
return t.tv_sec + t.tv_usec*1e-6;
}
#endif
#endif
结果的正确格式是什么benchmark.h
and benchmark.c
?
我知道头文件应该包含函数声明,而源文件应该是实际函数所在的位置定义居住。下面的代码正确吗?即,应该#ifdef WIN32
指令是否存在于我下面的两个文件中?或者应该全部都在.c
file?
benchmark.h
#ifndef BENCHMARK_H
#define BENCHMARK_H
#ifdef WIN32
#include <windows.h>
#else
#include <sys/time.h>
#include <sys/resource.h>
#endif
double get_time();
#endif
benchmark.c
#ifdef WIN32
double get_time()
{
LARGE_INTEGER t, f;
QueryPerformanceCounter(&t);
QueryPerformanceFrequency(&f);
return (double)t.QuadPart/(double)f.QuadPart;
}
#else
double get_time()
{
struct timeval t;
struct timezone tzp;
gettimeofday(&t, &tzp);
return t.tv_sec + t.tv_usec*1e-6;
}
#endif
头文件和 c 文件一起形成“代码模块”(或者如果您愿意的话:ADT、类等)。
头文件始终被视为用户界面您的代码,其中“用户”是要使用您的模块的程序员。它绝不能包含任何代码或变量定义,句号。
而c文件包含实际的实现,这对用户来说不感兴趣,也不应该引起他们的任何关注。 c 文件应该使用私有封装,用户不需要知道的所有内容都应该在该文件中。
以上是设计 C 程序或任何语言的任何程序的方式。这不是主观的,不是基于意见的,这是唯一的方法。如果您以不同的方式进行程序设计,那么您就做错了。
至于你的具体程序,应该按以下方式设计:
基准测试.h
#ifndef BENCHMARK_H
#define BENCHMARK_H
double get_time (void);
/* documentation about how this function is used should be put here */
#endif
基准测试.c
#include "benchmark.h"
/*** Include files ***/
#ifdef WIN32
#include <windows.h>
#else
#include <sys/time.h>
#include <sys/resource.h>
#endif
/*** Other stuff, for example constants, typedefs, static file scope variables ***/
/*** function definitions ***/
#ifdef WIN32
double get_time (void)
{
LARGE_INTEGER t, f;
QueryPerformanceCounter(&t);
QueryPerformanceFrequency(&f);
return (double)t.QuadPart/(double)f.QuadPart;
}
#else
double get_time (void)
{
struct timeval t;
struct timezone tzp;
gettimeofday(&t, &tzp);
return t.tv_sec + t.tv_usec*1e-6;
}
#endif
注意double get_time()
在 C 中表示“接受任何参数的函数”。这种风格很差,请使用void
反而。 C 和 C++ 在这方面是不同的。在 C++ 中,func()
and func(void)
意思是一样的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)