Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Coming up with errors for undefined references in main.c. This is because I have several files in this fashion:

main.c
{
    #include "somefile.h"
    somfunct() <--- undefined reference error
}

somefile.h
{
    somefunct() declaration
    ...
}

somefile.c
{
    #include "somefile.h"
    somefunct() definition
    ...
}

I am trying to use proper organization in that I use only declarations in the header files and define them in a separate file. After splitting up my code I get the undefined reference error because there is no link between somefile.h and somefile.c. Even though main.c includes the somefile.h header file, there is nothing in somefile.h that explicitly mentions somefile.c, so my functions are only partially defined. What is the proper way to take care of this problem? Many thanks. I hope this is clear let me know if not.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
253 views
Welcome To Ask or Share your Answers For Others

1 Answer

Here's a complete and working example of your goal.

main.c

#include "somefile.h"

int main() {
    somefunc();
    return 0;
}

somefile.h

#ifndef RHURAC_SOMEFILE_H
#define RHURAC_SOMEFILE_H

void somefunc();

#endif

somefile.c

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

void somefunc() {
    printf("hello
");
}

example build ( gcc )

gcc main.c somefile.c -o main

output

$ ./main 
hello

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...