vendredi 6 mars 2015

compile and run c++ program with own header files in linux


this is my first go at making my own header file. I am trying to make simple hello world program in C++ on ubuntu. made 3 files as follows :


//hello.h file



#ifndef HELLO_H
#define HELLO_H

//my own code

void hello();

#endif


//hello.cpp file



#include <iostream>
#include "hello.h"

using namespace std;

void hello()
{
cout << "This line is printed from header.";
}


//main.cpp file



#include <iostream>
#include "hello.h"

using namespace std;

int main()
{
cout << "in main" << endl << endl;
hello();
return 0;
}


i've tried "anubhav@anubhav-Inspiron-3421:~/Desktop/hello$ g++ -I /home/Desktop/hello/ -c hello.cpp -o hello.o " to compile header file and this command worked.


then, while doing "anubhav@anubhav-Inspiron-3421:~/Desktop/hello$ g++ -o main main.cpp". I am ending up with following error:


/tmp/ccb0DwHP.o: In function main': main.cpp:(.text+0x2e): undefined reference tohello()' collect2: error: ld returned 1 exit status


plz suggest whether changes need to be made in any file or in any command in the terminal?


thank you




Aucun commentaire:

Enregistrer un commentaire