LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   how to compile c++ class in linux (https://www.linuxquestions.org/questions/linux-newbie-8/how-to-compile-c-class-in-linux-809932/)

renuaseri 05-25-2010 01:36 AM

how to compile c++ class in linux
 
hi all ,
i am new in c++ progreming .
i have written lot of classes and main class of c++ in one file and compile successfully but now i have written all classes in different and main class in different file like this.

my one class is "rect.h"

#include <iostream>
using namespace std;

class CRectangle {
int x, y;
public:
void set_values (int,int);
};

\\this is another "rect.cpp"
#include <iostream>
using namespace std;
#include "rect.h"
void CRectangle::set_values (int a, int b) {
x = a;
y = b;
}

//this is main class "rect_main.cpp"
#include <iostream>
using namespace std;
#include "rect.h"
int main () {
CRectangle rect;
rect.set_values (3,4);
cout << "area: " << rect.area();
return 0;
}




now how to compile and run these classes

Nylex 05-25-2010 01:42 AM

First of all, you don't need the lines

#include <iostream>
using namespace std;

in either of your class files (rect.cpp and rect.h), because you're not using them in there. Also, you haven't declared the function area() in your class, so your program isn't going to compile.

Secondly, you need to use g++ to compile. You need to pass the main file as well as the class implementation file:

g++ rect_main.cpp rect.cpp -o rect_main

The -o option here sets the name of the executable file. If you don't use it, the executable will be called a.out. Edit: to run the executable, you simply do ./rect_main (the '.' is necessary here, because the current directory (for which '.' is shorthand) is not likely to be in your PATH).


All times are GMT -5. The time now is 09:56 PM.