开发者

include function definitions present in .c files in main

I ha开发者_C百科d to write few functions which are very long. So, I decided to put them in different files and link them to main.. so that it works as if I wrote function definitions after main().

How do I do it..


In a .h file you put your prototype

#ifndef MY_HEADER_H
#define MY_HEADER_H
void hello(void);
#endif

In a seperate .c file you implement your function such as hello.c

#include "myheader.h"
void hello()
{
    printf("Testing function from other file\n");
}

then in main you do

#include "myheader.h"

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

make sure you compile hello.c into hello.o before linking the files or it will tell you that it can't resolve the reference to hello.


Find create a header file that has a file ending of .h . Lets say this header file is named blah.h.

The general structure of this header will be

#ifndef BLAH_H_INCLUDED
#define BLAH_H_INCLUDED

//code

#endif // BLAH_H_INCLUDED

Those are header guards, to prevent multiple inclusions. Inside the code you will still your function declarations.

For example, void function(int blah); would be a valid function declaration.

This file is then included at the top of all of your files that uses or defines the functions declared, #include "blah.h"

Then you can define your functions in the other files, and when you link them together the program will work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜