Tag Archives: undefined reference to XXX error

C++ compiler prompt “undefined reference to…”[How to Fix]

Write a simple C + + clock class, put into the header file, the main function in the call header file compilation error, the specific code is as follows:

clock.h:

#include <iostream>
using namespace std;

class Clock
{
    private:
        int h,m,s;
    public:
        Clock();
        ~Clock();
        void SetTime(int h,int m,int s);
        void AddOneS();
        void ShowTime();
};
void Clock::SetTime(int h,int m,int s)
{
    
    this->h = h;
    this->m = m;
    this->s = s;
}
void Clock::ShowTime()
{
    cout<<h<<":"<<m<<":"<<s<<endl;
}

Main function:

#include "clock.h"   //When calling custom headers, use "" instead of<>
using namespace std;

int main(void)
{
    Clock c1,c2;
    c1.SetTime(2,45,36);
    c2.SetTime(6,40,34);
    c1.ShowTime();
    c2.ShowTime();
return 0;
}

Error prompt:

Check the error because “reference clock:: clock() and clock:: clock() are not defined”

It turns out that there is no function body for constructors and destructors

(1) : define function body in class: clock () {} ~ clock () {}

(2) : define function body outside class: void clock:: clock() {} void clock:: ~ clock() {}

Linux: How to Fix undefined reference to `itoa’

I wrote a simple C program in Linux, which used Itoa. But when compiling, I prompted “undefined reference to ` Itoa ‘”, I thought it would be OK to add – LC, but the result was the same. Internet found that some people say that this function does not exist in Linux, generally use sprintf to replace it. Look at the following code and comments:

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

int num = 0;
char namebuf[100];
char prefix[] = "/tmp/tmp/p";

char* gentemp()
{
    int length, pid;

    pid = getpid();
    strcpy(namebuf, prefix);
    length = strlen(namebuf);
    //itoa(pid, &namebuf[length], 10);      // Unix version: itoa() does not exist in header file <stdlib.h>
    sprintf(namebuf+length, "%d", pid);     // Converting integers to strings using sprintf
    strcat(namebuf, ".");
    length = strlen(namebuf);
    printf("before do...while\n");
    char command[1024] = {0};
    do 
    {
        //itoa(num++, &namebuf[length], 10);
        sprintf(namebuf+length, "%d", num++);
        sprintf(command, "touch %s", namebuf);  // Creating files via touch
        system(command);
        printf("command = %s, namebuf[%d]=%d\n", command, num-1, num-1);
    } while (num < 50 && access(namebuf, 0) != -1); // access to determine whether a file exists
    printf("end of do...while\n");

    return namebuf;
}

int main( void )
{
    char *p = gentemp();
    printf("%s\n", p);

    return 0;
}