Search code examples
c++g++undefined-reference

C++ undefined reference to defined function


I cannot figure out why this is not working. I will put up all three of my files and possibly someone can tell me why it is throwing this error. I am using g++ to compile the program.

Program:

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

using namespace std;

int main()
{
  char sentence[MAX_SENTENCE_LENGTH];
  char writeTo[] = "output.txt";
  int distanceTo,likePosition, length, numWords;
  cout << "ENTER A SENTENCE!   ";
  cin.getline(sentence, 299);
  length = strlen(sentence);
  numWords = wordCount(sentence, length);
  for(int x = 0; x < 3; ++x)
  {
    likePosition = likePos(numWords);
    distanceTo = lengthTo(sentence, likePosition, length);
    insertLike(sentence, distanceTo, length, writeTo);
  }
  return 0;  
}

Function file:

void insertLike(const char sentence[],  const int lengthTo, const int length, char writeTo[])
{
  char part1[MAX_SENTENCE_LENGTH], part2[MAX_SENTENCE_LENGTH];
  char like[] = " like ";
  for(int y = 0; y < lengthTo; ++y)
    part1[y] = sentence[y];
  for(int z = lengthTo+1; z < length - lengthTo; ++z)
    part2[z] = sentence[z];
  strcat(part1, like);
  strcat(part1, part2);
  writeToFile(sentence, writeTo);
  return;
}

Header file:

void insertLike(const char sentence[], const int lengthTo, const int length, const char writeTo[]);

The error exactly is:

undefined reference to 'insertLike(char const*, int, int, char const*)'
collect2: ld returned 1 exit status

Solution

  • The declaration and definition of insertLike have different writeTo parameters.

    In your header file, you have:

    void insertLike(const char sentence[], const int lengthTo, 
                    const int length, **const char writeTo[]**);
    

    while in your function file:

    void insertLike(const char sentence[],  const int lengthTo, 
                    const int length, **char writeTo[]**);
    

    C++ allows function overloading, where you can have multiple functions/methods with the same name, as long as they have different arguments. The argument types are part of the function's signature.

    In this case, insertLike which takes const char* as its fourth parameter and insertLike which takes char * as its fourth parameter are different functions.