5

Do stand alone C++ functions need a header file and a code file?

I am writing some C++ functions that use some of my other C++ classes but don't belong in a class themselves. They are intended to be compiled in a dll and so I was wondering if it was necessary to declare them in a separate header file or if I could/should just put the declarations in the .cc file.

Maybe this would just be bad practice?

3 Answers 3

2

The header file is useful because it is able to let other source files know about the functions that are declared in a different translation unit.

This is necessary by the compiler to be able to check that what you are invoking is correct for the type checker. But the necessity comes from the declaration itself not from the existence of the header file.

For a DLL, if I remember correctly, you are not forced to do it just because you are going to declare the signature of the function anyway whenever you are using them, eg.

extern C __declspec(dllimport) void foo();

Of course this means that you will need to forward declare them anyway so I don't see any problem in having an header files for your DLL, it will just keep all signatures together.

Sign up to request clarification or add additional context in comments.

Comments

2

It is not strictly necessary, but it is strongly recommended.

Place the function declarations in a header file and the function definitions in a source (.cc) file. The motivation is to allow the users (here, fellow programmers) to view only the interface but not the implementation (since it can change). Moreover, it allows other source files to include your header file and use the functions provided by you.

The only exception are static functions, they should not be declared in a header file because they are not supposed to be viewed or used outside your source file..

Comments

1

If you are going to use a function outside of the source file in which it's defined, you absolutely need a declaration. It is best to put the declaration in a header file so that it's consistent, otherwise you just end up repeating yourself and introducing a potential source of bugs.

8 Comments

+1 for being the first person to answer one of my questions!
So that's how he's built up such a reputation.
@PeterWood, the key is to be early, correct, and helpful. I always try to get at least one out of three. Getting started when SO was in beta in 2008 didn't hurt either.
What is the idea in using const qualifiers like const char * in function declarations in a header?
@user129393192 that's a bit beyond the scope of this question. You use it to show that the function won't be changing the value you pass in.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.