0

I have to implement a simple c++ code, given an external library written in c. I am not able to use the functions that are in the library due to the following error:

/usr/bin/ld: /tmp/ccIpTi43.o: in function `main':
main.cpp:(.text+0x42): undefined reference to `given_function`'
collect2: error: ld returned 1 exit status

Here is my file main.cpp

#include <stdio.h>
#include <iostream>
using namespace std;

extern "C"{
    #include "fake_receiver.h"
}

int main(){
    int i = given_function("file.log");

    cout << "Success " << i << endl;

    return 0;
}

Note: the file exists in the repo and has data written in ti Then, the fake_receiver.h:

#pragma once

#define MAX_CAN_MESSAGE_SIZE 20

int given_function(const char* filepath);

And the fake_receiver.c file itself:

#include "fake_receiver.h"

#include <time.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

static int current_line_count = 0;
static int next_start_stop = 50;
static int start_or_stop = 0;
static int line_count = 0;
static int opened = 0;
static FILE* can = NULL;

int given_function(const char* filepath){
    if(opened == 1)
        return -1;

    can = fopen(filepath, "r");

    if(can == NULL)
        return -1;
    srand(time(NULL));
    opened = 1;

    char c;
    while((c = fgetc(can)) != EOF){
        if(c == '\n'){
            line_count ++;
        }
    }
    fseek(can, 0, SEEK_SET);

    return 0;
}

I am new to c++ programming, so I don't really know how to solve this and make the function work properly. If you know, please help me

Matteo Possamai
  • 455
  • 1
  • 10
  • 23
  • 1
    Have you linked the library? Or looked how "undefined reference" questions get solved here? – Quimby Sep 20 '22 at 11:56
  • 6
    How do you compile and link your code? – Gerhardh Sep 20 '22 at 11:57
  • *"Note: the file exists in the repo and has data written in ti"* -- since your error stops you before an executable is created, functionality is not yet a concern. – JaMiT Sep 20 '22 at 12:26
  • 2
    Unless you can provide some details that will distinguish your question from [What is an undefined reference/unresolved external symbol error and how do I fix it?](https://stackoverflow.com/a/12574400), I have to view this as a duplicate. *Note: that link goes to the answer I find most likely to be applicable, but there are other answers.* – JaMiT Sep 20 '22 at 12:29
  • 1
    It helps to know that `ld` is the linker. Your program compiled okay but failed to link because it did not have all the pieces needed. Each C file needs to be compiled, then all the compiled objects linked together. – stark Sep 20 '22 at 12:42

0 Answers0