[英]How to split this into header and source files?
我有一些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
和benchmark.c
的正確格式是什么?
我知道頭文件應包含函數聲明 ,而源文件應位於實際函數定義所在的位置。 下面的代碼正確嗎? 即, #ifdef WIN32
指令是否應該同時存在於兩個文件中? 還是應該全部放在.c
文件中?
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
頭文件和ac文件一起構成一個“代碼模塊”(或者,如果您將:ADT,類等)。
頭文件始終被視為代碼的用戶界面 ,其中“用戶”是將使用您的模塊的程序員。 它絕不包含任何代碼或變量定義,句點。
盡管c文件包含實際的實現,但對於用戶而言這並不重要,因此他們不應該關心它們。 c文件應使用專用封裝,並且用戶不需要的所有內容都應在該文件中。
以上是設計C程序或任何語言的任何程序的方式。 這不是主觀的,不是基於觀點的,這是唯一的方法。 如果您以不同的方式進行程序設計,那么您做錯了。
對於您的特定程序,應按以下方式進行設計:
benchmark.h
#ifndef BENCHMARK_H
#define BENCHMARK_H
double get_time (void);
/* documentation about how this function is used should be put here */
#endif
benchmark.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()
和func(void)
含義相同。
我將其簡化為這一點,頭文件中唯一需要的就是函數原型。
benchmark.h
double get_time();
benchmark.c
#ifdef WIN32
#include <windows.h>
#include "benchmark.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>
#include "benchmark.h"
double get_time()
{
struct timeval t;
struct timezone tzp;
gettimeofday(&t, &tzp);
return t.tv_sec + t.tv_usec*1e-6;
}
#endif
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.