Hello, I’m Liang Tang.

This is part 44 of the EasyC++ series on joint compilation.

If you want a better reading experience, you can visit github repository: EasyLeetCode.

The joint compilation

In the previous article, we wrote the header file coordin.h, and now we need to complete its implementation.

The header file contains only definitions of life and constants, not implementations. So we’ll put the implementation in a separate CPP file. Since our header file is called coordin.h, our corresponding CPP file is naturally called coordin.cpp.

In coordin.h we declared two functions, and naturally we need to implement them:

#include <cstdio>
#include <iostream>
#include <cmath>
#include "coordin.h"

using namespace std;

polar rect_to_polar(rect xypos) {
    polar answer;
    answer.distance = sqrt(xypos.x * xypos.x + xypos.y * xypos.y);
    answer.angle = atan2(xypos.y, xypos.x);
    return answer;
}

void show_polar(polar dapos) {
    const double rad_to_deg = 57.29577951;

    cout << "distance = " << dapos.distance;
    cout << ", angle = " << dapos.angle * rad_to_deg;
    cout << " degress" << endl;
}
Copy the code

One of these two functions converts from cartesian to polar coordinates, and the other one outputs polar coordinates, including a radian to Angle conversion.

Finally, let’s look at the main function:

#include "coordin.h"
using namespace std;

int main(a) {
	rect rplace;
	polar pplace;
	while (cin >> rplace.x >> rplace.y) {
		pplace = rect_to_polar(rplace);
		show_polar(pplace); }}Copy the code

One small detail is that we introduced coordin.h with double quotes instead of <>. Because if Angle brackets are used, the C++ compiler will look for the standard header in the file system where it is stored, or in the current or source directory if double quotes are used.

Also, although the function implementation we are using is implemented in coordin.cpp, we do not need to include it. I’m going to connect it later when I compile.

Now that our code is written, but we have two CPP files, how do we compile and run them?

We can compile CPP code into object code using the g++ -c command.

g++ -o coordin.cpp
Copy the code

After compiling, we will have a coordin.o file, and we will continue compiling main.cpp file:

g++ -o main.cpp
Copy the code

This gives us two.o files, and finally, we need to connect the two.o files together to program an executable:

g++ coordin.o main.o -o cur
Copy the code

Of course, we can also combine the compile and join steps of main.cpp together:

g++ main.cpp coordin.o -o cur
Copy the code

The advantage of compiling each file separately is that the coordin.cpp file is not compiled when, for example, we only need to change main.cpp, thus saving the compile run time. As we all know, compilation for large C++ projects is very time consuming.

Of course, in large projects, we usually don’t compile the project manually, but use automatic compilation scripts such as make.