我之前的习惯是将定义的函数全部放在头文件中。但是在 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:
通用方法
将exe文件路径赋值到cmd命令窗里(打开cmd只要在电脑中搜索一下即可)
Visual Studio
Project -> *** Properties -> Debugging -> Command Arguments
Qt Creator
不加命令行:
加入命令行:
Project -> Run -> Command line arguments
See also
Teddy van Jerry 的导航页
关于 C++中 Separate Compilation(分离式编译)无 return 的编写(函数为void)的思考
【C++ Primer(5th Edition) Exercise】练习程序 - Chapter6(第六章)