How to Create Multi-Module Programs

本文档详细介绍了如何在C和C++中构建多文件程序。主要内容包括:程序模块划分原则、公共与私有部分定义、头文件的正确使用方式、函数与全局变量的作用域设定,以及一些实用的编程技巧。

http://www.drpaulcarter.com/cs/module.php

1. Introduction

This document describes how to construct multi-file programs in Cand C++.

The first task is to decide how your program will be dividedinto multiple files or modules. If your program design containsADT's then usually each ADT's code should be in it's own file.Other functions should be grouped by their purpose. For example,all procedures that produce graphics might be stored in one file.

The next task is to determine what parts of a module is private(i.e., not needed by other modules) and what parts are public.These parts include functions, types and variables. In general,there should be a good reason for all public objects. (This isknown as encapsulation.)

2. Header Files

The public parts of a module must be stored in a header (.h)file. This header is included by files that use its corresponding module and the module itself. Thisinsures that the module and the files that use the module agreeon types and functions. Header files typically contain macros,typedef's and function prototypes. In C++, they also containclass definitions, inline code, template definitions andconstants. Remember that even when compiling several files, thecompiler looks at each file separately. Each file must includeheaders for all the info that the compiler needs to compile it.

It is also very common for headers to include other headers.This can lead to problems when header x.h and header y.h areincluded in a file, but both headers also include z.h. So header z.h is included twice. Most of time this will cause a compiler error, because of multiple declarations of a type or macro. There is a solution to this problem using the conditionalcompilation features of the preprocessor. The followingillustrates the solution:

#ifndef UNIQUE_MACRO_NAME
#define UNIQUE_MACRO_NAME

/* body of header */

#endif

The body of the header is only seen by the compiler ifUNQIUE_MACRO_NAME is not defined, then it is immediatelydefined. Thus, the body of the header is only included once, thefirst time the header is encountered by the compiler. Afterward,the macro is defined which keeps the body from being includedagain. Of course, each header file must use a different macro!

3. Functions and Global Variables

Functions and global variables by default have externalscope. This means that if function f is defined infile x.c, then it is available to use in filey.c or any other file. The linker combines the objectfiles (.o or .obj) into a single executablefile. Part of the linker's job is to match up global names that filesreference to their definition in another file. However, iff is part of the implementation of module x,then there is no reason that any other file should usef. In this case, f should instead be definedwith internal scope. Internal scope means that only the codein x.c can directly access function f. Togive a function internal scope, prefix its definition by the reservedword static. This is somewhat confusing, becausestatic has an entirely different meaning when used withlocal variables of a function. One technique to clarify this processis to use macros with the more meaningful names, PUBLICand PRIVATE.

#define PRIVATE static
#define PUBLIC

PUBLIC is defined to be nothing because functions have externalscope by default. Now to define a function with internal scope, use:

PRIVATE void f()

Of course, private functions are not prototyped in header files.

Global variables work much like functions. To give a globalvariable internal scope precede its definition by static (orbetter PRIVATE ). For a file to use a PUBLIC global variable, it must declare it as an extern variable. This is commonly done in the header file. (Global variables should be used sparingly and for good reasons only.)

Only one file has a PUBLIC function named main. This function is where execution begins just as in a single-file program.

The make utility is very useful for maintaining multi-module programs.

4. Do's and Don'ts

  • Never include code in header files! (Actually in C++, the rule is never include non-inline or non-template code in header files!)
  • If using Borland's Project Make to build multi-module programs, never include header files in the Project Make window!
  • If using a command-line compiler (like cc), do not compile the header files!
  • Never include source files!

5. Example

This section shows a multi-module program example:

File: header.h
#ifndef HEADER_EXAMPLE
#define HEADER_EXAMPLE

typedef long int INT32;      /* Used in prototype below so must be in header */
  
void f( INT32 );             /* external scope function prototypes go in header */

#endif
File: sub.c
#include <stdio.h>
#include "header.h"          /* " " in include causes compiler to look 
                                for header in the current working dir */

typedef double Real;         /* This type only used internally to this file, so 
                                it's not in header file */
static void g( INT32, Real );  /* internal scope function prototypes do not 
                                  go in header */

void f( INT32 x )
{
  g(x, 2.5);
}

static void g( INT32 x, Real d )
{
  printf("%f\n", x/d);
}
File: main.c
#include <stdio.h>
#include "header.h"

int main( void )
{
  INT32 x;

  printf("Enter a integer: ");
  scanf("%ld", &x);
  f(x);
  return 0;
}

One could compile this on UNIX with the command:

cc main.c sub.c

Note that the header file is not listed!


Maintainer: Paul Carter ( email: pacman128@gmail.com )
Copyright © 2002 All Rights Resevered
Last Updated: Thu Oct 10 09:17:44 CDT 2002
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值