在 FreeDOS 上如何使用 C 语言编程
C 语言
![](/data/attachment/album/202304/20/153041cl4dqmq46p63vl6l.jpg)



> 
> 在 FreeDOS 上使用 C 语言编程与在 Linux 上使用 C 语言编程非常类似。
> 
> 
> 


当我第一次开始使用 DOS 时，我喜欢 DOS 自带的 BASIC 来编写游戏和其它一些有趣的程序。很长时间后，我才学习 C 编程语言。


我马上爱上了使用 C 语言做开发！它是一种简单易懂的编程语言，在编写有用的程序时，这给予我很大的灵活性。实际上，很多 FreeDOS 的核心实用程序都是使用 C 语言和汇编语言编写的。


因此，FreeDOS 的 1.3 RC4 包含一个 C 语言可能并不出人意料，此外还有其它编程语言的编译器。FreeDOS 的 1.3 RC4 LiveCD 包含两个 C 编译器：Bruce's C 编译器（一个简单的 C 编译器）和 OpenWatcom C 编译器 。在 Bonus CD 上，你也可以找到 DJGPP（一款基于 GNU 的 GCC 的 32 位 C 编译器）和 GCC 的 IA-16 移植（需要 386 或更好的 CPU 来编译，但是，生成的程序可以在低端系统上运行）。


在 FreeDOS 上使用 C 语言编程与在 Linux 上使用 C 语言编程非常类似，但是有两个例外：


1. **你需要知道你使用了多少内存。** Linux 允许程序使用很多内存，但是 FreeDOS 有很多限制。DOS 程序只使用四种 [内存模式](https://devblogs.microsoft.com/oldnewthing/20200728-00/?p=104012)（大、中、紧凑和小）中的其中一种，具体取决于它们需要多少内存。
2. **你可以直接访问控制台终端。** 在 Linux 上，你可以创建 *文本模式* 的程序，使用一个诸如 ncurses 之类的库来绘制终端屏幕。但是，DOS 允许程序访问控制台终端和视频硬件。这为编写更有趣的程序提供了极大的灵活性。


我喜欢在 GCC 的 IA-16 移植或 OpenWatcom 中编写我的 C 程序，具体取决于我正在编写的是哪种程序。OpenWatcom C 编译器更容易安装，因为它只是个单一的软件包。这就是为什么我们在 FreeDOS 的 LiveCD 中提供 OpenWatcom 的原因, 在你安装 FreeDOS 的 1.3 RC4 时，如果你选择 “<ruby> 完全的安装（包括安装应用程序和游戏） <rt>  Full installation including applications and games </rt></ruby>”，那么你也自动地安装 OpenWatcom。如果你选择安装 “<ruby> 纯 DOS 系统 <rt>  Plain DOS system </rt></ruby>”，那么，你将需要使用 FDIMPLES 软件包管理器来安装 OpenWatcom C 编译器。


![安装 OpenWatcom](/data/attachment/album/202304/20/153110kzhje7k76aoisi6i.png "Installing OpenWatcom on FreeDOS 1.3 RC4")


*在 FreeDOS 1.3 RC4 上安装 OpenWatcom*


### 在 DOS 上使用 C 语言编程


你可以在 [OpenWatcom 项目网站](http://openwatcom.org/) 找到文档和库指南，以学习 OpenWatcom C 编译器所提供的独特的关于 DOS 的 C 语言编程库。简单描述几个最有用的函数:


来自 `conio.h` 头文件：


* `int getch(void)`：从键盘上获取一个按下的单个按键
* `int getche(void)`：从键盘上获取一个按下的单个按键，并回显该按键


来自 `graph.h` 头文件：


* `_settextcolor(short color)`：设置打印文本时的颜色
* `_setbkcolor(short color)`：设置打印文本时的背景颜色
* `_settextposition(short y, short x)`：移动光标到行 `y` 和 列 `x`
* `_outtext(char _FAR *string)`：从当前光标位置开始，直接将一串字符打印到屏幕


DOS 只支持 [16 种文本颜色](https://opensource.com/article/21/6/freedos-sixteen-colors) 和 8 种背景颜色。你可以使用值 0（黑色）到 15（亮白色）来具体指定文本颜色，以及使用值 0（黑色）到 7（白色）来具体指定背景颜色:


* `0`：黑色
* `1`：蓝色
* `2`：绿色
* `3`：品蓝色
* `4`：红色
* `5`：品红色
* `6`：棕色
* `7`：白色
* `8`：亮黑色
* `9`：亮蓝色
* `10`：亮绿色
* `11`：亮品蓝色
* `12`：亮红色
* `13`：亮品红色
* `14`：黄色
* `15`：亮白色


### 一个花哨的 “Hello world” 程序


很多新开发者学习编写的第一个程序是为用户打印 “Hello world” 。我们可以使用 DOS 的 `conio` 和 `graphics` 库来制作一个更有趣的程序，并使用彩虹般的颜色打印 “Hello world” 。


在这个实例中，我们将遍历每种文本颜色，从 0（黑色）到 15（亮白色）。随着我们打印每一行，我们都将为下一行缩进一个空格。在我们完成后，我们将等待用户按下任意按键，然后，我们将重置屏幕并退出。


你可以使用任何文本编辑器来编写你的 C 源文件代码。我喜欢使用一些与众不同的编辑器，如 [FreeDOS Edit](https://opensource.com/article/21/6/freedos-text-editor) 和 [Freemacs](https://opensource.com/article/21/6/freemacs)，但是，我最近一直在使用 [FED editor](https://opensource.com/article/21/1/fed-editor) ，因为它提供 *语法高亮* 功能，使其很容易在我的程序源文件代码中看到关键字、字符串（LCCT 译注：C 语言中没有字符串）、变量。


![编写一个简单的 C 程序](/data/attachment/album/202304/20/153110v2m28mkiinrmmntr.png "Writing a simple test program in C")


*使用 C 语言编写一个简单的测试程序*


在你使用 OpenWatcom 编译前，你将需要设置 DOS 的 [环境变量](https://opensource.com/article/21/6/freedos-environment-variables)，以便 OpenWatcom 可以找到它的支持文件。OpenWatcom C 编译器软件包中包含了一个为你做这件事的设置 [批处理文件](https://opensource.com/article/21/6/automate-tasks-bat-files-freedos)：`\DEVEL\OW\OWSETENV.BAT`。运行这个批处理文件可以自动为你的 OpenWatcom 设置环境变量。


在你的开发环境准备好后，你可以使用 OpenWatcom 编译器来编译这个 “Hello world” 程序。我已经将我的 C 源文件文件保存为 `TEST.C` ，因此，我可以输入 `WCL TEST.C` 来编译和连接该程序为一个名称为 `TEST.EXE` 的 DOS 可执行文件。在 OpenWatcom 的输出信息中，你将看到 `WCL` 实际上调用 OpenWatcom C 编译器（`WCC`）来编译，并调用 OpenWatcom 链接器（`WLINK`）来执行 <ruby> 对象/目标 <rt>  object </rt></ruby> 链接阶段：


![使用 OpenWatcom 编译](/data/attachment/album/202304/20/153110fnswgbll31tmlnmg.png "Compiling the test program with OpenWatcom")


*使用 OpenWatcom 编译测试文件*


OpenWatcom 会打印一些无关的输出信息，这可能会使发现错误和警告变得困难。为了告诉编译器来抑制这些大量的额外信息，请在编译时使用 `/Q`（“Quiet”）选项：


![使用 OpenWatcom 编译](/data/attachment/album/202304/20/153111a60sjj5jc0cjs01c.png "Use the /Q (\"Quiet\") option to make OpenWatcom print less output")


在编译 C 源文件文件时，如果你没有看到任何错误信息，那么你现在就可以运行你的 DOS 程序了。这个 “Hello World” 示例的程序名称是 `TEST.EXE` 。在 DOS 命令行中输入 `TEST` 来运行新的程序，你应该会看到这个非常漂亮的输出:


![运行测试程序](/data/attachment/album/202304/20/153111c4hiwfbhbyhzyi4h.png "You can create beautiful programs in C")


C 语言是一种非常高效的编程语言，在像 DOS 之类的资源有限的系统上进行编程也可以很好的工作。在 DOS 上，你可以使用 C 语言来做更多的事。如果你是 C 语言的初学者，那么，你可以跟随我们在 FreeDOS 网站上的 《[使用 C 语言编写 FreeDOS 程序](https://www.freedos.org/books/cprogramming/)》 的自学电子书，以及在 [FreeDOS YouTube 频道](https://www.youtube.com/freedosproject) 上的配套的 <ruby> 入门指南 <rt>  how-to </rt></ruby> 系列视频，来自主学习 C 语言。


*（题图：MJ:Legacy sci-fi computer programming::1.7 celestial::1 edison bulb::1 satellite imagery::1 wooden::1 in high resolution, very detailed, 8k）*




---


via: <https://opensource.com/article/21/6/program-c-freedos>


作者：[Jim Hall](https://opensource.com/users/jim-hall) 选题：[lujun9972](https://github.com/lujun9972) 译者：[robsean](https://github.com/robsean) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
When I first started using DOS, I enjoyed writing games and other interesting programs using BASIC, which DOS included. Much later, I learned the C programming language.

I immediately loved working in C! It was a straightforward programming language that gave me a ton of flexibility for writing useful programs. In fact, much of the FreeDOS core utilities are written in C and Assembly.


So it's probably not surprising that FreeDOS 1.3 RC4 includes a C compiler—along with other programming languages. The FreeDOS 1.3 RC4 LiveCD includes two C compilers—Bruce's C compiler (a simple C compiler) and the OpenWatcom C compiler. On the Bonus CD, you can also find DJGPP (a 32-bit C compiler based on GNU GCC) and the IA-16 port of GCC (requires a '386 or better CPU to compile, but the generated programs can run on low-end systems).

Programming in C on FreeDOS is basically the same as C programming on Linux, with two exceptions:

**You need to remain aware of how much memory you use.**Linux allows programs to use lots of memory, but FreeDOS is more limited. Thus, DOS programs used one of four[memory models](https://devblogs.microsoft.com/oldnewthing/20200728-00/?p=104012)(large, medium, compact, and small) depending on how much memory they needed.**You can directly access the console.**On Linux, you can create*text-mode*mode programs that draw to the terminal screen using a library like*ncurses*. But DOS allows programs to access the console and video hardware. This provides a great deal of flexibility in writing more interesting programs.

I like to write my C programs in the IA-16 port of GCC, or OpenWatcom, depending on what program I am working on. The OpenWatcom C compiler is easier to install since it's only a single package. That's why we provide OpenWatcom on the FreeDOS LiveCD, so you can install it automatically if you choose to do a "Full installation including applications and games" when you install FreeDOS 1.3 RC4. If you opted to install a "Plain DOS system," then you'll need to install the OpenWatcom C compiler afterward, using the FDIMPLES package manager.

![Installing OpenWatcom on FreeDOS 1.3 RC4 installing OpenWatcom](https://opensource.com/sites/default/files/uploads/install-ow.png)

opensource.com

## DOS C programming

You can find documentation and library guides on the [OpenWatcom project website](http://openwatcom.org/) to learn all about the unique DOS C programming libraries provided by the OpenWatcom C compiler. To briefly describe a few of the most useful functions:

From `conio.h`

:

`int getch(void)—`

Get a single keystroke from the keyboard`int getche(void)—`

Get a single keystroke from the keyboard, and echo it

From `graph.h`

:

`_settextcolor(short color)—`

Sets the color when printing text`_setbkcolor(short color)—`

Sets the background color when printing text`_settextposition(short y, short x)—`

Move the cursor to row`y`

and column`x`

`_outtext(char _FAR *string)—`

Print a string directly to the screen, starting at the current cursor location

DOS only supports [sixteen text colors](https://opensource.com/article/21/6/freedos-sixteen-colors) and eight background colors. You can use the values 0 (Black) to 15 (Bright White) to specify the text colors, and 0 (Black) to 7 (White) for the background colors:

**0**—Black**1**—Blue**2**—Green**3**—Cyan**4**—Red**5**—Magenta**6**—Brown**7**—White**8**—Bright Black**9**—Bright Blue**10**—Bright Green**11**—Bright Cyan**12**—Bright Red**13**—Bright Magenta**14**—Yellow**15**—Bright White

## A fancy "Hello world" program

The first program many new developers learn to write is a program that just prints "Hello world" to the user. We can use the DOS "conio" and "graphics" libraries to make this a more interesting program and print "Hello world" in a rainbow of colors.

In this case, we'll iterate through each of the text colors, from 0 (Black) to 15 (Bright White). As we print each line, we'll indent the next line by one space. When we're done, we'll wait for the user to press any key, then we'll reset the screen and exit.

You can use any text editor to write your C source code. I like using a few different editors, including [FreeDOS Edit](https://opensource.com/article/21/6/freedos-text-editor)** **and [Freemacs](https://opensource.com/article/21/6/freemacs), but more recently I've been using the [FED editor](https://opensource.com/article/21/1/fed-editor) because it provides *syntax highlighting*, making it easier to see keywords, strings, and variables in my program source code.

![Writing a simple test program in C writing a simple C program](https://opensource.com/sites/default/files/uploads/fed-test.png)

Before you can compile using OpenWatcom, you'll need to set up the DOS [environment variables](https://opensource.com/article/21/6/freedos-environment-variables)** **so OpenWatcom can find its support files. The OpenWatcom C compiler package includes a setup [batch file](https://opensource.com/article/21/6/automate-tasks-bat-files-freedos) that does this for you, as `\DEVEL\OW\OWSETENV.BAT`

. Run this batch file to automatically set up your environment for OpenWatcom.

Once your environment is ready, you can use the OpenWatcom compiler to compile this "Hello world" program. I've saved my C source file as `TEST.C`

, so I can type `WCL TEST.C`

to compile and link the program into a DOS executable, called `TEST.EXE`

. In the output messages from OpenWatcom, you can see that `WCL`

actually calls the OpenWatcom C Compiler (`WCC`

) to compile, and the OpenWatcom Linker (`WLINK`

) to perform the object linking stage:

![Compiling the test program with OpenWatcom compiling with OpenWatcom](https://opensource.com/sites/default/files/uploads/wcl-test.png)

OpenWatcom prints some extraneous output that may make it difficult to spot errors or warnings. To tell the compiler to suppress most of these extra messages, use the `/Q`

("Quiet") option when compiling:

![Use the /Q ("Quiet") option to make OpenWatcom print less output compiling with OpenWatcom](https://opensource.com/sites/default/files/uploads/wcl-q-test.png)

If you don't see any error messages when compiling the C source file, you can now run your DOS program. This "Hello world" example is `TEST.EXE`

. Enter `TEST`

on the DOS command line to run the new program, and you should see this very pretty output:

![You can create beautiful programs in C running the test program](https://opensource.com/sites/default/files/uploads/test.png)

C is a very efficient programming language that works well for writing programs on limited-resource systems like DOS. There's lots more that you can do by programming in C on DOS. If you're new to the C language, you can learn C yourself by following along in our [Writing FreeDOS Programs in C](https://www.freedos.org/books/cprogramming/) self-paced ebook on the FreeDOS website, and the accompanying "how-to" video series on the [FreeDOS YouTube channel](https://www.youtube.com/freedosproject).

## 1 Comment