3
himake: hello.o printing.o name.o
    g++ -o himake hello.o printing.o name.o

hello.o: hello.cpp
    g++ -c hello.cpp

printing.o: printing.cpp
    g++ -c printing.cpp

name.o: name.cpp
    g++ -c name.cpp

Running the above makefile gives me this error below:

[alex@pcc Dir]$ make g++ -o himake hello.o printing.o name.o

hello.o: In function `main':

hello.cpp:(.text+0xc8): undefined reference to `printHello(std::basic_string, std::allocator >)'

collect2: ld returned 1 exit status

make: *** [himake] Error 1

Files: hello.cpp:

// hello.cpp

// standard library
#include <iostream>
#include <string>
using namespace std;

// user defined header files
#include "name.h"
#include "printing.h"

int main ()
{
    string name;

    name = getName();   // getName is in name.h
    printHello(name);  // printHello is in print.h

    return 0;
}

name.cpp

// name.cpp

// user defined header files
#include "name.h" 
#include "printing.h"

string getName()
{
    string name;
    printGreeting();    // printGreeting is from print.h
    getline(cin, name);  
    return name;
}

name.h

// name.h

#include <iostream>
using namespace std;

string getName();

printing.cpp

// printing.cpp

// user defined include files
#include "printing.h"

void printGreeting(void)
{
    cout << "Your name: ";
    return;
}

void printHi (string  name)
{
    cout <<  "Hi, " << name << endl;
    return;
}

printing.h

// printing.h

#include <iostream>
using namespace std;

void printGreeting();
void printHello(string);
Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
fman
  • 230
  • 2
  • 10
  • 3
    If that code is accurate, the function printHello is not defined. Function name needs to be an exact match – Sergio Basurco Feb 23 '17 at 07:07
  • 3
    `printHi` or `printHello`? – Some programmer dude Feb 23 '17 at 07:10
  • oh my god, that was it – fman Feb 23 '17 at 07:12
  • On an unrelated note, please read [“using namespace” in c++ headers](http://stackoverflow.com/questions/5849457/using-namespace-in-c-headers). Don't use `using namespace std;` in a header file. There are many examples of why its bad with a little searching. I also recommend reading [Why is “using namespace std” considered bad practice?](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). – Some programmer dude Feb 23 '17 at 07:13

1 Answers1

1

You are declaring printHello:

void printHello(string);

... which you then call, without ever defining it. Without a definition, the link fails. (This is nothing to do with the makefile).

Probably the printHi function defined in printing.cpp is supposed to be a definition for printHello.

davmac
  • 20,150
  • 1
  • 40
  • 68