1

This is my first go at making my own header file. I am trying to make a 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

g++ -I /home/Desktop/hello/ -c hello.cpp -o hello.o

to compile header file and this command worked.

then, while doing

g++ -o main main.cpp

I am ending up with following error:

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

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

thank you

2
  • 1
    You always should compile with g++ -Wall -Wextra -g Commented Mar 6, 2015 at 6:08
  • Options -c and -o together are not recommended (not to say prohibited). g++ warns of that. Commented Jan 18, 2019 at 22:09

3 Answers 3

9

You don't link to hello.o in the command below:

g++ -o main main.cpp

Try this:

g++ -o main main.cpp hello.o

Or for such simple program, just issue the command below:

g++ -o main main.cpp hello.cpp

For ease of use, create a makefile, then you just run make:

make

A simple makefile:

helloprogram: hello.h hello.cpp main.cpp

    g++ -o helloprogram main.cpp hello.cpp

clean:

    rm helloprogram
Sign up to request clarification or add additional context in comments.

2 Comments

When we use iostream or something like that, we do not compile using g++ main.cpp iostream.cpp. Why does that work and not our program?
@SahilArora No, the standard library is a dependency : shared libraries, that means they are either header only or already compiled (.so).
0

Put hello.h in Path2Hello;

g++ -o main -I Path2Hello main.cpp hello.cpp

ps: -I option to specify an alternate include directory (for header files).

Comments

-2

To compile and run a C language program, you need a C compiler. To setup a C language compiler in your Computer/laptop, there are two ways:

Download a full fledged IDE like Turbo C or Microsoft Visual C++, which comes along with a C language compiler. Or, you use any text editor to edit the program files and download the C compiler separately.

1 Comment

for more info refer to this link: studytonight.com/c/compile-and-run-c-program.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.