Classes interfering with each other on compile - c++

I'm working on a C++ project.
I had a class with its function, then I realized some of those functions weren't related to that class but were just math functions so I decided to move them on to a namespace.
My first question is, what is the appropriate file extension for a c++ namespace?
I have a constants.h file where I plan on saving global constants, for example PI.
Right now:
#include <math.h>
const double PI = M_PI;
I have the namespace I talked about before, right now is called: specificMath.h
#include <stdlib.h>
#include "constants.h"
... more code
I have a gaussian.cpp:
#include "gaussian.h"
#include "specificMath.h"
#include <iostream>
... more code
This file includes a main function that right now does nothing, I just can't get the whole project to compile without a main...
I have a gaussian.h where I'm not including anything, is that wrong?
A third class, which has no attributes, just methods (again, is this wrong? or not pretty?). truncatedFunctions.cpp
#include "specificMath.h"
#include <stdlib.h>
#include "truncatedFunctions.h"
#include "gaussian.h"
using namespace specificMath;
And its truncatedFunctions.h where, again, I'm not including anything.
And a fourth class where I include
#include "margin.h" //Its header, where I'm not including anything
#include "gaussian.h"
#include "specificMath.h"
using namespace specificMath;
When I "make" it, it seems to compile fine, but when it gets to the linking part I get A LOT of errors saying that things on my margin.cpp class were first defined in truncatedFunctions.cpp
I am going crazy. I have no idea why this is happening, or how to solve it. I would really appreciate if somebody could help me out, and please, any extra piece of advice would be great since I am really trying to learn as much as I can with this project. Thanks!

When I "make" it, it seems to compile fine, but when it gets to the linking part I get A LOT of errors saying that things on my margin.cpp class were first defined in truncatedFunctions.cpp
Did you define your functions in your specificMath.h? You should only declare those functions.
For example, if your specificMath.h contains function definitions like
#ifndef COOL_STUFF_NSPC
#define COOL_STUFF_NSPC
#include <iostream>
namespace coolstuff{
void print(void){std::cout << "I'm declared in a header file." << std::endl;
}
#endif
and you are using including this file in several others, the linker is going crazy. Including means copying. And so you've got yourself coolstuff::print defined several times. The better way (and the only possible way when using self-written functions in many files) is splitting your code into a header and implementation as you did in gaussian.
// coolstuff.namepace.h
#ifndef COOL_STUFF_NSPC
#define COOL_STUFF_NSPC
namespace coolstuff{
void print(void);
}
#endif
When you include coolstuff.namespace.h it will only declare functions. And you can declare the same function several times.
// coolstuff.namespace.cpp
#include <iostream>
#include "cs.h"
void coolstuff::print(void){
std::cout << "Hello world!" << std::endl;
}
The .cpp file contains the implementation of your functions. Now your linker won't get irritated because there is only one implementation of coolstuff::print and not n (where n is the number of #include "cs.namespace.h" you used) ones.
My first question is, what is the appropriate file extension for a c++ namespace?
There is no standard namespace extension. Use .h/.cpp for header/implementation and a self-defined prefix, something like 'nmspc' or 'nsc'. It's up to you.

It's hard to tell whether you've done anything wrong in your code (because you didn't show any of it), but the first thing to try is to "clean" your build and rebuild all your code. If the compiler (don't know what you're using) for some reason didn't compile all your modified modules, then it's not surprising that the linker is having trouble.
My first question is, what is the appropriate file extension for a c++ namespace?
In C++, header files are usually .h or .hpp. It doesn't matter to the compiler.
#include "gaussian.h"
#include "specificMath.h"
#include <iostream>
In general, it's a good idea to #include stuff from the standard library first, followed by your own things.
I have a gaussian.h where I'm not including anything, is that wrong?
No. If you don't need to include anything, don't include anything.

First, use include guards for the headers.
#ifndef MYHEADER_H
#define MYHEADER_H
//header contents
#endif
This will prevent the same header from being included twice in the same translation unit.
Second, don't define uncosnt stuff in the headers:
double x = 0;
this will cause all translation units to export that symbol.
Declare the variable extern in your header and provide a definition for it in an implementation file.

Related

Which of these two is the proper way to implement a header?

Should you include #include the header of your function declaration in the source file where you define the function?
I've tried both and it seems to work either way. I was wondering if either way is preferred or if one might cause an error in a different compiler
//header.h
#ifndef HEADER_H
#define HEADER_H
int squareVal (int);
#endif
//squareVal.cpp
//should I #include "header.h" here as well?
int squareVal (int val){
return (val*val);
}
//main.cpp
#include"header.h"
using namespace std;
int main(){
cout << squareVal(2) << endl;
}
Both ways seem to work. From my testing and research it sounds like the linker is able to find squareVal.cpp regardless of including the header in that file or not.
Use the #include directive. Put it at the top, in front of any other #include directives. That way, if there's a mistake in the header, the compiler will be more likely to find it. In particular, if you declare the function differently from the way you define it, the compiler will notice. If you don't pull in the header, translation units that use that header will see a different signature from the one that's been defined, and you'll get errors when you try to link. It's much easier when you see the problem early.
Whether it makes a difference, depends on the contents of the header.
In this specific case, because a function definition does not require a previous function declaration, the #include in squareVal.cpp is not (and never will be) necessary.
However, imagine if the header contained more than the function declaration? What if it defined some types needed by the function? What if it defined some constants needed by the function definition? Then you'd need an #include.
It is considered good practice to #include regardless, because then you do not need to think about this, and doing so is effectively free.
The compiler simply puts the WHOLE code from the header right where you insert the #include "header.h". So in this example, the declaration is before the definition of the function and it does nothing bad.

where to find the definition of a external variable?

Where can I find the definition of end_of_list? I searched the whole project from eclipse, but can't find the definition. But when put end_of_list as an expression when debug, I can see it's value, just don't where from which file to find it.
#pragma once
#include <cstdlib>
#include <cassert>
#include <utility>
#include <algorithm>
#include <drizzled/memory/sql_alloc.h>
#include <drizzled/visibility.h>
namespace drizzled {
....
#define DRIZZLED_API __attribute__ ((visibility("default")))
extern DRIZZLED_API list_node end_of_list; // where to find **end_of_list**
I can see two immediate possibilities.
The Eclipse search functionality is not up to scratch, either because it's buggy (unlikely) or the actual definition of that item is held somewhere outside its scope (say, for example, you're including a header that isn't in the project).
The actual definition is not in a source file at all but possibly in an object file or library, in which case you probably shouldn't be worried about the definition - it's "hidden" for reasons of encapsulation.
Granted, these are guesses, but it's the best I can do with the information given, and I'd at least like to think that they're educated guesses :-)
If you're using "extern" to declare it in your code, then it was defined in another source file that probably came compiled in the library you're using. See:
http://drizzle.org/lcov/drizzled/sql_list.cc.gcov.html

c++ #include style differences

So the other day, I was looking through some old C++ books and noticed a way of creating a C++ class I had never seen before. Everything I have seen up to that point had always used the #include "header.h" and compiled the implementation files separately. What I saw the author of this book do is actually put an include directive to the implementation at the end of the header file and omitting the .cpp file from the compilation. Has anybody used this style?
For Example:
I have
main.cpp
employee.h
employee.cpp
//main.cpp
#include <iostream>
#include <stdio.h>
#include <string>
#include "employee.h"
void main()
{/*some code*/}
//employee.h
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
class employee
{
public:
//public members
private:
//private members
}
#endif
//employee.cpp
#include "employee.h"
#include <string>
//public member definitions
I would normaly compile this project like so:
g++ main.cpp employee.cpp
But in the author's example is like this
//main.cpp
#include <iostream>
#include <stdio.h>
#include <string>
#include "employee.h"
void main()
{/*some code*/}
//employee.h
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
class employee
{
public:
//public members
private:
//private members
}
#include "employee.cpp" // <-- the line of code that caught my attention
#endif
//employee.cpp
#include <string>
//public member definitions
And the resulting code compiles as
g++ main.cpp
Is this merely a style preference or are there any real benefits in this? I would think it wouldn't scale very well, but I am not a super proficient C++ programmer either.
Doing this will bring the definition of the class in to every translation unit where the header file is included. This is a very unusual paradigm, and could be hazardous to your coding health. In particular, if you have main.cpp and foo.cpp both of which #include "employee.h", then all the methods on employee will be defined twice, which is a violation of the One Definition Rule and will create linker errors. In order to resolve those linker errors, you need to either move the definitions to their own translation unit, or mark them inline (which may or may not work).
This is however a useful idiom in some instances. Particularly with templates, which must be defined within the translation unit. In that case, when you want the declaration and implementation in separate files for readability, you can do an end-of-file #include. When I do this, I use a special file extension, .hpp to signify that the file is special in that it is not intended to be compiled on its own. See this answer for an example.
That approach is sometimes used when providing templates, and is equivalent to providing the template and implementation all in the header file, but allows humans to read the template declarations without going over the code. Equivalently, if you are providing inlined functions, it would be understandable (not going as far as recommended, but understandable) if you did the same.
For anything else, it is a bad approach. It not only requires all translation units to actually compile all of the function definitions, but it also requires you to declare all functions as inline, or include the header from a single translation, as otherwise it would trigger linker errors.
This is probably not a mainstream book. Anyway, if we define correctness by the condition of "it compiles", then yes, it is a matter of style, and both styles are correct.
However, the only truly correct style, according to the standard, and design guidelines that match other programming languages, is the first one, matching the spirit of separate compilation of translation units. As you yourself said, the second style would not scale very well.
Another point would be that #include <stdio.h>, which is not standard any more:
#include <cstdio>
This will certainly work, but it has a couple of downsides:
Longer compilation times - normally if you change one file, you only need to compile that one file and the linker will combine it with the other older compilation results. When everything is included into a single file, everything needs to be recompiled at once.
Potential namespace collision - any symbols declared in one module are now visible to all of them. This can be a big problem if you use any macros.
This is actually a trick I have seen in build systems where for nightly builds to speed them up, including all cpp file in one and them compiling it can generate some big gains in overall speed.

Pulling C/C++ standard library into your project namespace, good idea?

I'm porting some open source code so that it can build on another c++ compiler. One of the difficulties and themes that seem to keep cropping up are implementation differences of the provided standard library by the compiler.
For example, one of the source files that I'm compiling includes <sys/types.h>. However, it gives me the following errors:
Error E2316 g:\Borland\BCC593\Include\sys/types.h 45: 'time_t' is not a member of 'std'
Error E2272 g:\Borland\BCC593\Include\sys/types.h 45: Identifier expected
After looking at the root cause of this I found that one of the main include headers of the project is including <sys/types.h> in this pattern:
project_source1.cpp:
#include "../TargetPlatform.h"
#include "project_config.h"
#include <windows.h>
namespace project_namespace {
#include "project_component/all.h"
// more project includes down here
// ...
}
project_component/all.h:
#ifndef INCLUDE_GUARDS
#define INCLUDE_GUARDS
#include <sys/types.h>
#include "project_header1.h"
#include "project_header2.h"
// and other headers etc..
// followed with class definitions and what not.
#endif
This is all well and good except for one problem, the <sys/types.h> is implemented something like this for the compiler I'm porting to:
<sys/types.h> trimmed to the essence:
namespace std {
typedef long time_t;
typedef short dev_t;
typedef short ino_t;
typedef short mode_t;
typedef short nlink_t;
typedef int uid_t;
typedef int gid_t;
typedef long off_t;
} // std
using std::time_t;
using std::dev_t;
using std::ino_t;
using std::mode_t;
using std::nlink_t;
using std::uid_t;
using std::gid_t;
using std::off_t;
And this is the cause of the compile error I'm seeing. Because the project is including <sys/types.h> inside its own namespace, things like time_t, off_t, dev_t etc get put into the scope project_namespace::std:: which is obviously not what's intended.
What's the best way to handle this? Keep in mind there could be other standard library headers defined in a similar fashion and not just sys/types.h. Are there any C++ idioms that's relevant or semi-related to this issue(or possibly even at odds with it due to the way this is implemented)? If so, how can it be reconciled?
Thanks
This is a bad idea. Do not do things this way. Put the namespace declarations inside each header file. Never have a #include directive inside the scope of a namespace.
Never is a strong word, and there are very rare cases in which you might want to do this. If the file you're #includeing also has #include directives, you almost certainly do not want to be doing this, even more so than if they didn't.
If you need to be able to easily rename your namespace or use the same header to declare the same symbols in several different namespaces depending on context, use the preprocessor to change the namespace name instead. That's extremely ugly to do, but much better than what you're currently doing.
One thing you can do as a quick and dirty solution to this is #include <sys/types.h> and any other system header that's included before the namespace declaration. This will cause the double-inclusion guards in the system header files to kick in and avoid declaring stuff inside the namespace.
I would say you need to change the offending code so that the standard types are no longer defined within project_namespace.
It seems to me you have two major issues: [1] you have a catch-all header in project_all.h and [2] it's #included inside namespace project_namespace. I'll address the latter first. If your project has things it wants to put in its own namespace, that's fine, but it should be done as follows:
// Foo.h
// includes go here
namespace project_namespace {
class Foo { ... }
}
// Foo.cpp
// includes go here
namespace project_namespace {
// Foo implementation goes here
}
... in other words, your classes' header and implementation files need to say what namespace the classes belong in, "self-namespacing" as it were. All your #includes are outside a namespace because the header file for each class declares the namespaces the class belongs to. This is the convention used by the standard library.
Now if you still want to use a project_all.h you can do so. Without the namespace -- because each header file will place its declarations in the namespace it wants to (or not).
But it would be better to dispense with project_all.h; instead, #include the header files individually and make the dependencies explicit. And if the response is "there are too many header files", that's probably a sign of a high degree of coupling between your components.
I realize this is probably not the answer you wanted, sorry ...

#include anywhere

Is the #include <file> meant to be used for headers only or is it simply a mechanical "inject this code here" that can be used anywhere in the code?
What if I use it in the middle of a cpp function to just "inject" code from a single source? will this work or will compilers scream about this?
It is a mechanical inject the code here device. You can include a text file containing Goethe's Faust if you wish to. You can put it anywhere, even in the middle of a function (of course, #include needs a fresh line!).
However, it's strong convention to only use #include for header files. There may be reasons where I wouldn't object on it, for example pulling in machine-generated code or merging all translation units in a single file.
Not only does it work anywhere, but it can lead to some interesting techniques. Here's an example that generates an enumeration and a corresponding string table that are guaranteed to be in sync.
Animals.h:
ANIMAL(Anteater)
ANIMAL(Baboon)
...
ANIMAL(Zebra)
AnimalLibrary.h:
#define ANIMAL(name) name,
enum Animals {
#include "Animals.h"
AnimalCount
};
#undef ANIMAL
extern char * AnimalTable[AnimalCount];
AnimalLibrary.cpp:
#include "AnimalLibrary.h"
#define ANIMAL(name) #name,
char * AnimalTable[AnimalCount] = {
#include "Animals.h"
};
main.cpp:
#include "AnimalLibrary.h"
int main()
{
cout << AnimalTable[Baboon];
return 0;
}
Be sure not to put the usual include guards in any file that will be included multiple times!
Gotta agree with William Pursell though that this technique will have people scratching their heads.
Compilers will not complain, but everyone who has to maintain the code will.
It will work - more or less its semantic meaning is: place code in that file here
EDIT: For abusing usages of #include I can just recommend the following:
#include "/dev/console"
This allows for everything: a one-liner that can do everything, an error, its just a matter of compilation...
Should work, it's processed by your preprocessor, your compiler won't even see it.
#include and other preprocessor directives like #define or #import, can appear anywhere in the source, but will only apply to the code after that inclusion. It is meant to include the referenced code into the source file that calls it.
This MSDN page explains it quite well. http://msdn.microsoft.com/en-us/library/36k2cdd4(v=VS.71).aspx
include is handled by the preprocessor and is a mechanism to inject code. There are no restrictions on the file being included or where this #include is placed in your code (thought it should be in its own line). As long as the file specified can be found by the preprocessor it will import its contents into the current file.
Conventionally you do this for header files. I've seen this being done with cpp files during template instantiation (with proper #ifdef so you don't include it multiple times causing multiple symbol definition error).
If you have a long constant, you can do this for other file types as well. (Though there are better ways of handling long string constants)