Home > Blockchain >  undefined reference to `function' in only 1 file c,
undefined reference to `function' in only 1 file c,

Time:02-21

i have a c file named main.c

#include <stdio.h>
extern int main(int argc, char* argv[], char* envp[]);
void start(){
    ...;
    int return_code = main(argc, argv, envp);

    exit(return_code);
}

you can see I declared main but when using ld to link it:

$ (use ld to link, I didn't write it down because it's quite verbose and irrelevant)
ld: bin/test.o: in function `start':
/home/user/Desktop/test/test.c:28: undefined reference to `main'
make: *** [Makefile:49: link] Error 1

so what should i do (sorry if this is a simple question for you)

CodePudding user response:

Generally speaking, invoking ld yourself is being a glutton for punishment. Use your C compiler to link until proven otherwise.

gcc -o bin/test bin/test.o will link a C program for you.

It looks like you tried to "fix" it by providing _start yourself. You can't (in C). _start is not a function.

CodePudding user response:

In C you have to define a main function that will be called automatically by your program, this is the base of your code.

I saw that you include "stdio.h" which is a library allowing to have access to some function like for example in my program the function "printf". If you don't need it then don't include it :)

For example here is how to make your first program with a main function.

#include <stdio.h>

int main(int argc, char *argv[]){
    
    ... // Your code

    printf("Hello world"); // Just print on your terminal this string
    return (0); // 0 is the default return code if there is no errors 
}
  •  Tags:  
  • c ld
  • Related