3

I have a main.cpp file and a read.c file. I am calling a function read_int from main function which is defined in read.c file. Also i have declared the function in read.h file and i have included the file in main.cpp. But when i try to compile I am getting "undefined reference to read_int" error.

the commands used for compiling are:

gcc -c ./input/read.c -o ./bin/input/read.o

gcc ./main.cpp ./bin/input/read.o -o ./bin/main.out

the main.cpp file :

#include<stdio.h>
#include "./input/read.h"
int main() {
    int *vectorA = (int *) malloc(sizeof(int)*VECTOR_A_SIZE);
    int *vectorB, *matrixA, *matrixB;
    int *flags = (int *)malloc(sizeof(int)*4);
    flags[0] = 1;
    read_int(vectorA, vectorB, matrixA, matrixB, flags);
}

the read.c file is

 #include<stdio.h>

 int read_int(int *vectorA, int *vectorB, int *matrixA, int *matrixB, int *flags) {
 int flag_count = 4;
 int err = 0;
 FILE *fp = fopen("input_int.txt","R");
 int i,j;
 if(flags[0]) {
     for(i = 0; i < VECTOR_A_SIZE; i++) {
         fscanf(fp, "%d", (vectorA + i));
     }
 }
 fclose(fp);
 return 0;
}

the read.h file is

int read_int(int *vectorA, int *vectorB, int *matrixA, int *matrixB, int *flags);
Johns Paul
  • 633
  • 6
  • 22

2 Answers2

3

This is because when you include the header in your C++ file, the name "read_int" is "mangled".
The C++ compiler decorates the name with type information in order to enable overloading.

You need to tell the C++ compiler that it's actually a C function.
This is done with the linkage specifier extern "C".

Put this in "read.h":

#ifdef __cplusplus
extern "C" {
#endif 

int read_int(int *vectorA, int *vectorB, int *matrixA, int *matrixB, int *flags);

#ifdef __cplusplus
}
#endif 

And remember to include "read.h" in your C file as well, or everything will break mysteriously if you change the function's protype in one place and forget about the other.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82
0

Shouldn't it be

#include "read.h"

in the top of read.c?

And read.h should contain

#ifndef READ_H
#define READ_H
…
#endif
Vercetti
  • 437
  • 1
  • 6
  • 17