[Notes] The idea of Separate Compilation in C++ (including the test of function command line parameters)

My previous habit was to put all the defined functions in the header file. But in the reminder of C++ Primer 6.1, I learned that there are security risks.

But the book (English Version Page 207) is very confusing, especially the .cc suffix was not found at all. After searching, I know that for Windows, .cpp is more commonly used.

It seems that the chain does not seem to be so difficult. Just include the header files together.

The following is the topic of Exercise 6.9 . (At the same time, it is also an experiment of the command line parameters of Exercise 6.25 & 6.26 function )


Title (Exercise 6.9)


Header Files:

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

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;
}

The following procedurePerform their duties

  • Chapter6.h:statementfunction
  • fact.cpp:definitionfunction
  • factMain.cpp: main program

Test of function command line parameters (Exercise 6.25 & 6.26)

Change 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;
Insert picture description here

Why not? ? ?
Which is the Command-line? It's not right to lose by the book! ! !
0

1
2


See also

Teddy van Jerry's navigation page
thoughts on C++ Separate Compilation without return writing (function is void)
[C++ Primer(5th Edition) Exercise] Exercise program-Chapter6 (Chapter 6)

Guess you like

Origin blog.csdn.net/weixin_50012998/article/details/108297540