Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

c - Proper use of header files

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...