Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ways not to write function headers twice?

Tags:

c++

c

header

I've got a C/C++ question, can I reuse functions across different object files or projects without writing the function headers twice? (one for defining the function and one for declaring it)

I don't know much about C/C++, Delphi and D. I assume that in Delphi or D, you would just write once what arguments a function takes and then you can use the function across diferent projects. And in C you need the function declaration in header files *again??, right?. Is there a good tool that will create header files from C sources? I've got one, but it's not preprocessor-aware and not very strict. And I've had some macro technique that worked rather bad.

I'm looking for ways to program in C/C++ like described here http://www.digitalmars.com/d/1.0/pretod.html

like image 749
mee Avatar asked May 26 '10 13:05

mee


Video Answer


2 Answers

Imho, generating the headers from the source is a bad idea and is unpractical.

Headers can contain more information that just function names and parameters.

Here are some examples:

  • a C++ header can define an abstract class for which a source file may be unneeded
  • A template can only be defined in a header file
  • Default parameters are only specified in the class definition (thus in the header file)

You usually write your header, then write the implementation in a corresponding source file.

I think doing the other way around is counter-intuitive and doesn't fit with the spirit of C or C++.

The only exception is can see to that is the static functions. A static function only appears in its source file (.cor .cpp) and can't (obviously) be used elsewhere.

While I agree it is often annoying to copy the header definition of a method/function to the source file, you can probably configure your code editor to ease this. I use Vim and a quick script helped me with this a lot. I guess a similar solution exists for most other editors.

Anyway, while this can seem annoying, keep in mind it also gives a greater flexibility. You can distribute your header files (.h, .hpp or whatever) and then transparently change the implementation in source files afterward.

Also, just to mention it, there is no such thing as C/C++: there is C and there is C++; those are different languages (which indeed share much, but still).

like image 160
ereOn Avatar answered Oct 05 '22 02:10

ereOn


It seems to me that you don't really need/want to auto-generate headers from source; you want to be able to write a single file and have a tool that can intelligently split that into a header file and a source file.

Unfortunately, I'm not aware of any such tool. It's certainly possible to write one - but you'd need a given a C++ front end. You could try writing something using clang - but it would be a significant amount of work.

like image 44
JoeG Avatar answered Oct 05 '22 02:10

JoeG