C++ undefined referencia a la función definida


No puedo entender por qué esto no está funcionando. Voy a poner los tres de mis archivos y posiblemente alguien puede decirme por qué está lanzando este error. Estoy usando g++ para compilar el programa.

Programa:

#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;  
}

Archivo de función:

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;
}

Archivo de cabecera:

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

El error es exactamente:

undefined reference to 'insertLike(char const*, int, int, char const*)'
collect2: ld returned 1 exit status
Author: Mashew, 2010-11-09

4 answers

La declaración y la definición de insertLike son diferentes

En su archivo de encabezado:

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

En su 'archivo de función':

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

C++ permite la sobrecarga de funciones, donde puede tener múltiples funciones/métodos con el mismo nombre, siempre y cuando tengan diferentes argumentos. Los tipos de argumento son parte de la firma de la función.

En este caso, insertLike que toma const char* como su cuarto parámetro y insertLike que toma char * como su cuarto parámetro son diferentes funciones.

 20
Author: Mud,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-06 00:40:27

Aunque los posters anteriores cubrieron su error particular, puede obtener errores de enlazador de 'Referencia indefinida' al intentar compilar código C con g++, si no le dice al compilador que use el enlace C.

Por ejemplo, debe hacer esto en sus archivos de encabezado C:

extern "C" {

...

void myfunc(int param);

...

}

Para hacer 'myfunc' disponible en programas C++.

Si todavía quieres usar esto desde C, envuelve los extern "C" { y } en #ifdef __cplusplus condicionales del preprocesador, como

#ifdef __cplusplus
extern "C" {
#endif

De esta manera, el bloque extern simplemente será "omitido" cuando se use un compilador de C.

 19
Author: MattK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-08 11:17:26

Necesitas compilar y enlazar todos tus archivos fuente:

g++ main.c function_file.c
 15
Author: casablanca,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-09 04:12:46

Esto también podría suceder si está utilizando CMake. Si ha creado una nueva clase y desea instanciarla, en la llamada del constructor recibirá este error-incluso cuando el encabezado y los archivos cpp son correctos - si no ha modificado CMakeLists.txt en consecuencia.

Con CMake, cada vez que cree una nueva clase, antes de usarla, el encabezado, los archivos cpp y cualquier otro archivo compilable (como los archivos Qt ui) deben agregarse a CMakeLists.txt y luego volver a ejecutar cmake . donde CMakeLists.txt está almacenados.

Por ejemplo, en este archivo CMakeLists.txt:

cmake_minimum_required(VERSION 2.8.11)

project(yourProject)

file(GLOB ImageFeatureDetector_SRC *.h *.cpp)

### Add your new files here ###
add_executable(yourProject YourNewClass.h YourNewClass.cpp otherNewFile.ui})

target_link_libraries(imagefeaturedetector ${SomeLibs})

Si está utilizando el comando file(GLOB yourProject_SRC *.h *.cpp) entonces solo necesita volver a ejecutar cmake . sin modificar CMakeLists.txt.

 2
Author: AxeEffect,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-04 22:04:22