综合编程

Undefined reference error even after connecting c files

微信扫一扫,分享到朋友圈

Undefined reference error even after connecting c files

This question already has an answer here:

  • “undefined reference to” errors when linking static C library with C++ code 1 answer

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

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.

Sparse files

上一篇

iPhone 9价格曝光:“史上最低”入手iPhone门槛

下一篇

你也可能喜欢

评论已经被关闭。

插入图片

热门栏目

Undefined reference error even after connecting c files

长按储存图像,分享给朋友