【笔记】 C++中 Separate Compilation(分离式编译)的思路 (包括函数命令行参数的试验)

我之前的习惯是将定义的函数全部放在头文件中。但是在 C++ Primer 6.1 的提醒中了解到这样是存在安全隐患的(同时 include 可能会报重定义的错误)。

对于链似乎也不想以为的那么困难。只要共同 include 头文件即可。

下面是 Exercise 6.9 的题目。(同时也是 Exercise 6.25 & 6.26 函数命令行参数的试验)


题目(Exercise 6.9)


Header Files:

  • Chapter6.h
#ifndef CHAPTER_6
#define CHAPTER_6
int factorial(unsigned n); // a declaration
#endif // !CHAPTER_6

或者:

#pragma once
#define CHAPTER_6
int factorial(unsigned n); // a declaration

Source Files:

  • fact.cpp
#include "Chapter6.h"

int factorial(unsigned n) // definition
{
	unsigned ret = 1;
	if (n)
	{
		for (unsigned i = n; i != 0; i--)
			ret *= i;
	}
	return ret;
}
  • factMain.cpp
#include <iostream>
#include "Chapter6.h"
using namespace std;

int main()
{
	unsigned num;
	cout << "Please enter a natural number: ";
	cin >> num;
	cout << num << "! = " << factorial(num) << endl;
	return 0;
}

以下程序各司其职

  • Chapter6.h:声明函数
  • fact.cpp:定义函数
  • factMain.cpp:主程序

函数命令行参数的试验(Exercise 6.25 & 6.26)

改动 factMain.cpp:

#include <iostream>
#include "Chapter6.h"
using namespace std;

int main(int argc, char *argv[])
{
	unsigned num;
	cout << "Please enter a natural number: ";
	cin >> num;
	cout << num << "! = " << factorial(num) << endl;

	// Test for Command-Line Options
	string str;
	for (int i = 1; i != argc; ++i) {
		str += argv[i];
		str += " ";
	}
	cout << str << endl;

	for (int i = 0; i < argc; i++)
	{
		cout << "argc[" << i << "]: " << argv[i] << endl;
	}

	return 0;
}

正常打开、不额外加入命令时的 Output:
output

通用方法

将exe文件路径赋值到cmd命令窗里(打开cmd只要在电脑中搜索一下即可)
1

Visual Studio

Project -> *** Properties -> Debugging -> Command Arguments
2
3
4

Qt Creator

不加命令行:
5

加入命令行:
Project -> Run -> Command line arguments
6

7


See also

Teddy van Jerry 的导航页
关于 C++中 Separate Compilation(分离式编译)无 return 的编写(函数为void)的思考
【C++ Primer(5th Edition) Exercise】练习程序 - Chapter6(第六章)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值