rablentain
rablentain

Reputation: 6715

Multiple header files to one source file?

I have a source file called source.c and a public header file called source.h. The source.c contain s

#include "source.h"

I do not want all the functions in source.c to be public, therefore I want another header file called priv_source.h that refers to some private functions in source.c.

Do the compiler understand that priv_source.h also is a header file to source.c or do I have to make another c-file called priv_source.c?

Upvotes: 2

Views: 2994

Answers (3)

asifaftab87
asifaftab87

Reputation: 1433

In C, by default, all functions are public, which means that a function declared inside any header can be used by other method if that source file simply includes the header. Now, if you explicitly declare a function like static return_type name(/*some arguments may or may not*/), then this can't be accessed outside of that file. Now, there is no such privilege to hide any function like Java, C++ and C# etc. I am not sure whether this can be achieved by using #if, #elif and #endif statements. You have to write logic for your function presented in your code, then put in #if. Because if an #if statement's if condition is not satisfied, then after preprocessor stage that part will vanish from our code similar to comments in our code. See I am not sure but may be.

Upvotes: -1

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

There are two points in your question:

  1. Function declarations are put into header files so that they can be included into multiple source files, without explicit need to declare in each and every source file. So, only put those declaration in header file which you WANT to be available to other files as well.
  2. If some function need to be restricted to a particular file, make that function definition as static. Once you define a function as static, it will not be visible from outside for linking. The scope of that function will be limited to the same compilation unit, usually that file only.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Do the compiler understand that priv_source.h also is a header file to source.c or do I have to make another c-file called priv_source.c?

C compiler does not make any such connection: all files, headers and sources, are unrelated to the compiler. All it knows is the name(s) of the translation units that it needs to process (i.e. the names of your .c files) and the names of headers that these translation units include.

It is common to split declarations in two parts - the public and the private ones. In such cases, however, the private header would include the public one, like this:

source.h

// Public declarations go here
void public_function1(int, int);
void public_function2(int, double, int);

priv_source.h

#include "source.h"
void private_function1(float);
void private_function2(char*);

source.c

#include "priv_source.h"

Upvotes: 9

Related Questions