C - Undefined reference to function error with linked files

笑着哭i 提交于 2021-02-18 18:09:30

问题


I started implementing a large program. But I ran into a massive issue. So here is very simplified code of my program. I have a separate .c file for my functions which is normal.c the main program is main.c and I have linked those two with cal.h header file.

main.c

#include <stdio.h>
#include "cal.h"

void main()
{
    int num1, num2, ans;
    num1=5;
    num2=5;
    ans=add(num1, num2);
    printf("%d" ,ans);
}

normal.c

#include "cal.h"

int add(int num1, int num2)
{
    return num1+num2;
}

cal.h

#ifndef CAL_H_INCLUDED
#define CAL_H_INCLUDED
#include <errno.h>

int add(int num1, int num2);

#endif // CAL_H_INCLUDED

but when I compile this, it gives out the error ..\main.c|10|undefined reference to `add'|

I'm using CodeBlocks v.13.12 in Windows 8.1 Any answer for this question is much appreciated. I tried with CodeLite as well, but the same error occurs. Thank you!


回答1:


Complete compilation of the code is required in ubuntu terminal use the following

gcc normal.c main.c -o out -lm



回答2:


Code blocks have automatic linking but for that you need to have your source and header files under a project.

I had the same issue when I made individual .c & .h files and expected the IDE to link the object files but it failed. I put them under a project and it worked!




回答3:


Use complete compilation of your code. if your c codefiles main.c and normal.c are in ./src and header file cal.h is in ./inc follow below method from current dir(.)

g++ ./src/main.c ./src/normal.c -I ./inc -o main

now main is out binary file to execute.



来源:https://stackoverflow.com/questions/24702645/c-undefined-reference-to-function-error-with-linked-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!