methods declared, but never defined in Geant4 source code - c++

During my searches through the Geant4 source code, I have noticed several times that there are methods which are declared in the header but are never defined with any associated code (pardon any falsities in my lingo (I'm an engineer)).
An example would be a method defined like:
G4TrackVector* GetfSecondary();
which has no implementation in the header or the source file, is not virtual, and yet it is used on various occasions by the program and the program runs from this compiled code. At first I thought it was just some cool code hiding trick with doxygen, but I now see it is not! This is a common occurrence in the code.
Could someone explain what's going on?
Thanks

The GetSecondary() function is a member of the G4Step class (defined in G4Step.hh) and is implemented inline in G4Step.icc. G4Step.icc is included at the end of G4Step.hh.
I'm guessing you were looking in the source directory instead of the include directory for the implementation, but the include dir is the propper place for inline implementation.
In the future if you are on *nix, you can try a grep -r <FunctionName> . from the top of the project directory to find all mentions of a function, which should include the implementation.

The code would fail to compile if this were the case. You just aren't looking in the right place for it's definition. Or just not noticing it. Calling a declared function with no definition is an error.

Related

Compile cpp without corresponding header

I've just been given my first real C++ application on the job after working through some books learning the language.
It was my understanding that your cpp source files required the cooresponding header, yet one of the libraries in my project is building fine with a number of cpp files that DO NOT include the cooresponding header. This particular cpp implements a class found in a header that has a different name and a number of other pieces of code beyond just the original class declaration.
How is it that the cpp can compile functions belonging to a class that it has no knowledge of?
Can the implementation of these functions be compiled independently and are simply called when a client application using the library (and including the header with the class declaration) calls the corresponding member function? If this is the case, how is the implementation binary referenced by the client application?
(I assume this is the linker...but I would love to have this cleared up).
I anticipate the answer may expose a misunderstanding of mine with regard to the include and compilation process, and I'd really like to learn this aspect of C++ well. Thank you!
When a c++ source file is compiled the first stage it goes through is preprocessing.
When the include directive is reached the file is found and the entire contents of the file, whatever that may be is included into the source file, as if it had been written in the source file itself.
You will be able to define any function from a class in any source file that includes the class's declaration, this is the source file "knowing" about the class / function".
There's also no requirement that the contents of a header and a source file will have any relationship. It's widely considered to be very good practise however.
The implementation of each compilation unit (a source file) is compiled independently. Any function definition could be placed in any compilation unit, and it would make not difference whatsoever. When the compilation units are linked together the usages of every declaration are matched to all the definitions.
The only other pattern that some people might use other than the 1:1 relationship between source files and header files (that I can think of) is that the header files each describe a class and each source file would implement a collection of related functionality. But this is a bad idea (in my opinion) because it would encourage the definitions of various classes to because highly coupled.
These are several questions. You should try to split these.
The name of the files where something is declared is not relavant. The compiler gets the preprocessor output independent from the files that have been read by the preprocessor. The compiler might be use some file/line information in the preprocessed file to issue more readable diagnostic messages.
When you declare a class in a header file and copy that declaration to a implementation file everything works fine as long as you don't change one of the copies of the declaration. This is bad dangerous and should be avoided. Declare anything always once.
When you compile an implementation of a class member function you get a function that the linker can link to your client program. A good tool chain is able to link only the functions that are accessed. So you can separate the interface (in the header files) from the implementation that is provided in a static library. The linker will add each object module in the library to your executable until all symbol references are resolved.

Are functions in C/C++ headers a no-go?

I'm working on a very tiny piece of C/C++ source code. The program reads input values from stdin, processes them with an algorithm and writes the results to stdout.
I would just implement all that in a single file, but I also want test cases for the algorithm (not the input/output reading), so I have the following files in my project:
main.cpp
sort.hpp
sort_test.cpp
I implement the algorithm in sort.hpp right away, no sort.cpp. It's rather short and doesn't have any dependencies.
Would you say that, in some cases, functions defined in headers are okay, even if they are sophisticated algorithms and not just simple accessors/mutators? Or is there a reason I should avoid this? When should I move code from header to source file?
There is nothing wrong with having functions in header files, as long as you understand the tradeoff. Putting them in a header file means they'll have to be compiled (and recompiled) in any translation unit that includes the header. (and they have to be declared inline, or you will get linker errors.)
In projects with many translation units, that may add up to a noticeable slowdown in compile times, if you do it a lot.
On the other hand, it ensures that the function definition is visible everywhere the function is called -- and that means that it can be trivially inlined, so the resulting program may run faster.
And finally, with function templates, you typically have no realistic alternative. The definition must be visible at the call site, and the only practical way to achieve that is to put it in a header.
A final consideration is that header-only libraries are easier to deploy and use. You don't need to link against anything, you don't have to worry about ABI's or anything else. You just add the headers to your project, include them and off you go.
Quite a few popular libraries use a header-only strategy.
When you put functions in headers you have to make sure to declare them inline. This is required to avoid a duplicate definition warning when more than one .cpp file include that header file. Generally you should only put small functions inside header files because it will be compiled for each cpp file that includes the header which will slow down compilation time and also results in code bloat; a larger executable file.
It's OK to put any function in the header as long as it's inline. Things such as functions defined inside class { } and templates are implicitly inline.
If the resulting application becomes too large, then optimize the code size. Optimizing before there is a problem is an anti-pattern, especially when there is a benefit to doing it "your way," and the fix is as simple as moving from one file to another and erasing inline.
Of course, if you want to distribute the code as a library, then deciding between a header, static library, or dynamic library binary is an important decision affecting the users.
The vast majority of the boost libraries are header-only, so I'd say: Yes, this is an established and accepted practice. Just don't forget to inline.
That really is a stile choice. But putting it in the header does mean that it will be inline code rather than a function. If you wanted that same functionality, you could use the inline keyword:
inline int max(int a, int b)
{
return (a > b) ? a : b;
}
http://en.wikipedia.org/wiki/Inline_function
The reason you should avoid this in general (for non inline functions) is because multiple source files will be including your header, creating linker errors.
It doesn't matter if you have a pramga once or similar trick - the duplication will show up if you have more than one compilation unit (e.g. cpp files) including the same header.
If you wish to inline the function, it MUST be in the header else it can't get inlined.
If you publish a header with your libraries and the header has some sort of implementation in it, you can be sure that after a few years if you change the implementation and it doesn't work exactly the same way as it did before, some peoples code will break since thay will have come to rely on the implementation they saw in the header. Yeah i know one should not do it but many people do look in header for the implementation and other behaviour they can exploit/use in a not intended way to overcome some problem they are having.
If you are planning to use templates then you have no choice but to put it all in header. (this might not be necessary if you compiler supports export templates but there is only 1 i know of).
Its ok to have the implementation in the header. It depends on what you need. If you separate the definition to a different file then the compiler will create symbols with external linkage if you dont want that you can define the functions inside the header itself. But you would be wasting some amount of memory for the code segment. If you include this header file in two different files then both files codes segment will have this function definition.
If other header file is going to have a function with similar name then its going to be a problem. Then you have to use inline.

Ways not to write function headers twice?

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
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).
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.
Considering you have declared some functions and wrote their implementation you will have a .c/cpp file and a header .h file.
What you must do in order to use those functions:
Create a library (DLL/so or static library .a/.lib - for now I recommend static library for the ease of use) from the files were the implementation resides
Use the header file (#include it) (you don't need to rewrite the header file again) in your programs to obtain the function definitions and link with your library from step 1.
Though >this< is an example for Visual Studio it makes perfect sense for other development environments also.
This seems like a rudimentary question, so assuming I have not mis-read,
Here is a basic example of re-use, to answer your first question:
#include "stdio.h"
int main( int c, char ** argv ){
puts( "Hello world" );
}
Explanation:
1. stdio.h is a C header file containing (among others) the definition of a function called puts().
2. in main, puts() is called, from the included definition.
Some compilers (including gcc I think ) have an option to generate headers.
There is always very much confusion about headers and source-files in C++. The links I provided should help to clear that up a little.
If you are in the situation that you want to extract headers from source-file, then you probably went about it the wrong way. Usually you first declare your function in a header-file, and then provide an implementation (definition) for it in a source-file. If your function is actually a method of a class, you can also provide the definition in header file.
Technically, a header file is just a bunch of text that is actually inserted into the source file by the preprocessor:
#include <vector>
tells the preprocessor to insert contents of the file vector at the exact place where the #include appears. This really just text-replacement. So, header-files are not some kind of special language construct. They contain normal code. But by putting that code into a separate file, you can easily include it in other files using the preprocessor.
I think it's a good question which is what led me to ask this: Visual studio: automatically update C++ cpp/header file when the other is changed?
There are some refactoring tools mentioned but unfortunately I don't think there's a perfect solution; you simply have to write your function signatures twice. The exception is when you are writing your implementations inline, but there are reasons why you can't or shouldn't always do this.
You might be interested in Lazy C++. However, you should do a few projects the old-fashioned way (with separate header and source files) before attempting to use this tool. I considered using it myself, but then figured I would always be accidentally editing the generated files instead of the lzz file.
You could just put all the definitions in the header file...
This goes against common practice, but is not unheard of.

Multiple files in Dev-C++, Linker Error. Templates

I apologise for what I'm pretty sure is a fairly stupid question, but I can't get it to work!
I'm also not sure what information is too much information so I probably won't give enough info so sorry for that too - just ask.
I began writing a class within main.cpp, and it got large so I decided to shift it to a different source file. I'm not too sure on how to do this, and can't figure anything to help fix this specific problem from internet resources (hence the asking).
I started off with the class definition including all of the function definitions above the main program function. This runs fine. I then split this up into two separate pieces. The class declaration (I think that's the correct term) above the main function and the function definitions below the main function.
This also runs perfectly well. I proceeded to cut the class declaration out into a header file. This header file is of the form
#ifndef INC_MATRIX_H
#define INC_MATRIX_H
class matrix{
//ETC
};
#endif
Which I have read somewhere is useful but I'm not entirely sure why, I think it's to stop redeclaration of the functions if the header is included more than once.
So currently we have this header file included along with the other includes. Then the main function and then the function definitions beneath the main function. This also compiles and runs perfectly well.
The next step I took was to cut the function definitions into their own separate .cpp file. The only addition that was made to this .cpp file was that some extra includes had to be added to the top (specifically iostream and cstdlib). ALSO the matrix.h file was included.
In this configuration Dev-C++ brings up linker errors when I try to compile and run the code. Specifically they are of the form
[Linker Error] undefined reference to matrix <bool>::matrix(int, int)
And the code doesn't run (obviously).
how can I fix this? Thanks in advance.
Edit: It's been discovered that this is due to the fact that it's a templated class and in the scope of the matrix.cpp file the template isn't introduced to the bool type. I now want to figure out how to fix this without adding lots of lines of code to individually make each function accept each given type.
Oh, and I appreciate that I can define the functions in the header. But I thought that we weren't meant to do that? I thought the idea was that you simply include the declaration.
The error suggests that your matrix class is a templated class. Is it? Perhaps posting the code would help.
If it is a templated class then see this FAQ for a description of the general problem with separating templated classes into header/implementation, and solutions to this problem.
I think you probably didn't add matrix.cpp to your project. It has to build that to matrix.o and link it to main.o to create your .exe.

How to define (non-method) functions in header libraries

When writing a header library (like Boost), can one define free-floating (non-method) functions without (1) bloating the generated binary and (2) incurring "unused" warnings?
When I define a function in a header that's included by multiple source files which in turn is linked into the same binary, the linker complains about redefinitions. One way around this is to make the functions static, but this reproduces the code in each translation unit (BTW, can linkers safely dereplicate these?). Furthermore, this triggers compiler warnings about the function being unused.
I was trying to look for an example of a free-floating function in Boost, but I couldn't find one. Is the trick to contain everything in a class (or template)?
If you really want to define the function (as opposed to declaring it), you'll need to use inline to prevent linker errors.
Otherwise, you can declare the function in the header file and provide its implementation separately in your source file.
You can use the inline keyword:
inline void wont_give_linker_errors(void)
{
// ...
}
Er... The answer to your question is simply don't. You just don't define functions in header files, unless they are inline.
'static' function can also be defined in headers, but it is only useful for very specific rare purposes. Using 'static' just to work around a multiple-definition problem is utter nonsense.
Again, header files are for non-defining function declarations. Why on Earth would you want to define functions there?
You said you are writing "header library". What's a "header library"? Please note, that Boost defines its "functions" in header files because their "functions" are not really functions, they are function templates. Function templates have to be defined in header files (well, almost). If that's wasn't the case, Boost wouldn't be doing something as strange as defining anything in header files.
Besides the already mentioned inline, with most compilers templates have to be defined in headers (and with all compilers it's allowed). Since boost is mostly templates, that explains why it is almost all headers.
People have suggested inline but that violates the very first part of your question i.e. it bloats the code as the full definition is inserted into the code at each call of the function. The answer to your overall question is therefore "No".
If you mark them as static then they are still defined in each source file as you rightly pointed out but only once and so that's a better option than inline if code size is the only issue. I don't know if linkers can, or are allowed to, spot the duplicates and merge them. I suspect not.
Edit:
Just to clear up any confusion as to whether I support the notion of using static and/or defining functions within headers files generally then rest assured I don't. This was simply meant as a technical response as to the differences between functions marked inline and static defined in header files. Nothing more.