I created a class and have some outside methods in a Functions.h header (think thats the problem). Anyway, when ever I try to use any type of C-style function in the class implementation file; even blank ones, I get a compiler/ liker error. I am new to this and don't understand what the problem is. I'm thinking I can't use the .h file, but I am able to use global vars and directives in the class file.
Where am I suppose to declare my outside functions? In what kind of file?
My guess is that you fully define the functions (including implementation) in a header file, and include that from multiple source files; and that the errors you forgot to describe say something about "multiple definitions" or "duplicate symbols":
// Header file
void some_function() {
// do some stuff
}
If that is the case, you need to either move the definitions into a source file, leaving just declarations in the header, so they only have a single definition:
// Header file
void some_function();
// Source file
void some_function() {
// do some stuff
}
or declare the definitions inline, which allows them to be included in more than one source file:
// Header file
inline void some_function() {
// do some stuff
}
If that isn't the problem, please post some example code and error messages so we don't have to guess what's happening.
You have c++ as a tag. Perhaps these functions are C++ functions but you're trying to get at them from an Obj-C file? If that's the case, you either need to turn them into C functions, or you need to use Obj-C++ (which has the .mm extension instead of .m).
Related
For C programs, I know I need .h, and .cpp to allow multiple .h to be read and compiled together but linked later.
However, for C++, I don't want to break up the class member function declaration and definition to two parts. Although it is the typical C++ way, I am trying to merge member function declaration and definition in one header file. I saw some people doing that. I would like to know if there is any problem to do this.
I know all members defined in .h class definition are then inline functions, but can they be non-inline in any way? Will compiler be controllable so that they don't have to be inline, for example, when the function is huge?
The VS2015 intellisense shows error when the 2s is in a member function defined in header file, but doesn't show that in cpp file. But it compiles. Is it showing that I am doing it wrong, or it's a bug for VS2015? I deleted the sdf, restarted the project, as long as copy the function into the .h file, it shows a read line under std::this_thread::sleep_for(2s);
see
class testtest {
void tryagain() {
using namespace std::chrono_literals;
auto twosec = 2s;
std::this_thread::sleep_for(2s);// problem is here
}
};
Is compiling faster if we separate the .h and .cpp?
My final compiler would be g++4.9.2, and I am using VS2015 to test build. The final code will run on an ARM with 1GB RAM on Linux.
I don't intend to argue about wich style is better, but hope to focus on whether it works, and what are the trade offs.
It is perfectly fine to place all implementation code in the .h file if you want, it usually depends on the situation. It's usually good practice to split up the interface and implementation even if all the code is in the .h file by doing something like this
class MyClass {
public:
void doSomethingUseful();
};
....
void MyClass::doSomethingUseful() {
// code goes here....
}
Not all functions will automatically be inlined, the compiler usually decides what to inline or not. Larger functions will likely not be inlined even if they're in the header. You can use the inline keyword to give a hint to the compiler that you'd like the function to be inlined but this is no guarantee (also as a small aside, functions marked as inline in a .cpp file will be inlined, but only when called from other functions within that same .cpp file)
Compile times will be slower with more code in the .h file so it's best to try and reduce the amount of code in them as much as possible. I guess in your case though it shouldn't be that noticeable.
I hope that is of some help! :)
You can put defines around functions to prevent them being implemented more than once
header file:-
class MyClass {
public:
void doSomethingUseful();
};
// inline functions
....
// non inline function
#ifdef MYCLASSCPP
void MyClass::doSomethingUseful() {
// code goes here....
}
#endif
Then define MYCLASSCPP in just one CPP file. (or complier parameter).
I have created a function library that I want to create a DLL from and create an export library. Creating the DLL is not the problem.
The problem is that, I do not want the developer/user to look inside the header file as the code is not optimized and some of it looks a mess even though it works.
Is there anyway I can include the contents of the header file within another DLL so that the header file will then be hidden or is there a way to compile the header to Binary?
Win32, visual studio 2010, 'c/c++'.
First, remove the code from the header: just declare the functions and specify the classes (i.e. no code in there):
//header
void my_ignomous_function(int);
class my_ignomous_class {
public:
my_ignomous_class();
~my_ignomous_class();
bool my_ignomous_member(my_ignomous_class &x);
private:
// unfortunately, you have to give these details.
};
If this is not sufficient, you could use the pimpl idiom: in your class you use a pointer to an object that is used for the implementation. The advantage is that you can just declare the implementation class without any details in the header. The details are only needed in the implementation.
//header
class my_nice_class {
public:
my_nice_class()
~my_nice_class()
bool my_nice_member(my_nice_class &x);
private:
class my_horrible_secret_class *impl;
};
The other approach is to fune-tune your design, so that you've no longer anything to hide ;-)
As already mentioned you have to separate Declaration and Definition [1]
Declaration in Header (.h), export only functions the developers need [2] - no need for a .def file.
The user has to know the Declarations of the functions he is using. So he needs the header.
Definition (function body - implementation) in Source file (.cpp)
Maybe you can split it up into more header/source - pairs so that the header for the Developers solely contains the clean "interface" of your library - the exported function.
https://www.cprogramming.com/declare_vs_define.html
https://learn.microsoft.com/en-us/cpp/build/exporting-from-a-dll-using-declspec-dllexport?view=msvc-170
I declare all variables and functions in .h file and has become my habit to do that (I'm programming with cocos2dx)
And I read that you should try to include the least in .h file and the most in .cpp file.
Because I declare all variables and functions in .h file, If I need to use another class from another file, then I need to include that class in the .h file to declare that class as a variable.
So I want to know the importance of declaring variables in .h file and .cpp file. I want to know which way is most standard as well.
If there is no difference, then why people would declare variables and functions in private file because declaring a function in .h file requires you to write it again in .cpp file.
ie)
.h file:
class classA {
private:
void function();
};
.cpp file:
void classA::function() {
...do something...
}
What is the importance of declaring variables and functions in header files?
Declare anything that is needed outside of the code in the .cpp file in the header file, and no more. Try to minimise the amount in there as much as possible. The reason for this is that other programmers could be looking at your header (.h) file, it is essentially their API. As an OOP programmer you want to hide as much of the internal workings of your objects as possible i.e. you do not want people using your API to become dependent on factors that may change as the structure of the objects does. Also try and keep the scope of your variables as low as possible. It is better to avoid global variables if you can in general. Passing them as parameters is almost always a better idea. Try to keep variables in the lowest scope possible.
Typically you would have your declarations inside a header file, and your definitions inside the cpp. There are many benefits to doing this, one of the biggest being re-usability. If you have multiple files that need to use a certain class, it is much easier to just include it where needed rather than having to re-declare it.
Being able to separate prototypes from the actual member bodies is also quite useful. This allows you to do things such as having a binary version of the implementation, and still keep the function names publicly available. This way if someone was using your class or library they could see how to use it, but not be able to see how it actually works. This is very important in larger projects and when copyright is involved.
This is a good habit to get into, but can get confusing and overwhelming if you don't stay organized. Common practice is to have an implementation file (.cpp) and a header (.h) for each class, both generally having the same name as the class to improve readability.
You should avoid using a header file just to declare local variables as it's generally best to keep them in the scope where they're needed.
As for your particular sample, you can avoid putting class private methods into the header file using the Pimpl Idiom. You'll have only publicly visible (public/protected) members declared in your header file, all the rest goes to the .cpp:
.h file:
class ClassA {
public:
ClassA();
~ClassA();
void foo();
private:
class ClassAImpl;
ClassAImpl* pImpl;
};
.cpp file:
#include "ClassA.h"
struct ClassAImpl
void function() {
// ...do something...
}
};
ClassA::ClassA()
: pImpl(new ClassAImpl()) {
}
ClassA::~ClassA() {
delete pImpl;
}
void ClassA::foo() {
pImpl->function();
}
Benefits of having a separate .h and .cpp file
Hide Implementation: You can separate the declaration from definition. So say you want to create an API, you could put your actual logic in .cpp (which becomes the library file on compilation) and have the declaration in .h which someone one could use to access the API.
Reduce Compilation time: One benefit of having definition in .cpp and declaration in .h is when you want to make changes to the definition. Such a change, would just change the cpp file and that .cpp will have to be recompiled. If the definition were to be in .h file, all the .cpp files where the .h file is included would have to be recompiled which would take more time.
Improves Readability: Having declaration and definition separate in some ways improves readability.
One of the reasons we have separate header and source files in C++ is because C++ code is unmanaged . It is directly executed by the processor (unlike C#, Java which are executed in a virtual environment). This requires having a header file to hold the symbol information which while being separate from the implementation, acts as an interface to it.
In C and C++, the order in which things are declared is important. Remember that when these languages were designed - compilers were not what they are today. Header files are things that you "include" which describe classes, type-definitions, enums. Now, you can provide implementation (and in the case of C++ template classes, you have to) in the header file. You put the implementation of the stuff in to the .cpp file. You're not writing a function twice (the compiler will have a hissy-fit if you do). You declare or implement them in the header file and then, in the case of the former, you implement them in the C++ file.
Consumers of your code (in a library project, for example), will include the header files (that describe the classes), and then link against an object file (as opposed to .cpp files). Header files provide you, ahead-of-time, the symbols to expect and link against.
Templates are a little weird in this respect (you don't export them), they are header file only (at the moment, I believe).
Modern languages such as C# do not have the concept of header files, because of the way the compiler works. The C# compiler looks at the files as a "whole" and therefore there is no need to forward declare anything or worry about header files. C/C++ compilers do not do this. I am unsure (without going and looking it up) whether or not this was due to compiler technology at the time or a concsious design decision at the time.
You are not duplicating code.
Thinking Time - Why do you want to split your file anyway?
As the title suggests, the end problem I have is multiple definition linker errors. I have actually fixed the problem, but I haven't fixed the problem in the correct way. Before starting I want to discuss the reasons for splitting a class file into multiple files. I have tried to put all the possible scenarios here - if I missed any, please remind me and I can make changes. Hopefully the following are correct:
Reason 1 To save space:
You have a file containing the declaration of a class with all class members. You place #include guards around this file (or #pragma once) to ensure no conflicts arise if you #include the file in two different header files which are then included in a source file. You compile a separate source file with the implementation of any methods declared in this class, as it offloads many lines of code from your source file, which cleans things up a bit and introduces some order to your program.
Example: As you can see, the below example could be improved by splitting the implementation of the class methods into a different file. (A .cpp file)
// my_class.hpp
#pragma once
class my_class
{
public:
void my_function()
{
// LOTS OF CODE
// CONFUSING TO DEBUG
// LOTS OF CODE
// DISORGANIZED AND DISTRACTING
// LOTS OF CODE
// LOOKS HORRIBLE
// LOTS OF CODE
// VERY MESSY
// LOTS OF CODE
}
// MANY OTHER METHODS
// MEANS VERY LARGE FILE WITH LOTS OF LINES OF CODE
}
Reason 2 To prevent multiple definition linker errors:
Perhaps this is the main reason why you would split implementation from declaration. In the above example, you could move the method body to outside the class. This would make it look much cleaner and structured. However, according to this question, the above example has implicit inline specifiers. Moving the implementation from within the class to outside the class, as in the example below, will cause you linker errors, and so you would either inline everything, or move the function definitions to a .cpp file.
Example: _The example below will cause "multiple definition linker errors" if you do not move the function definition to a .cpp file or specify the function as inline.
// my_class.hpp
void my_class::my_function()
{
// ERROR! MULTIPLE DEFINITION OF my_class::my_function
// This error only occurs if you #include the file containing this code
// in two or more separate source (compiled, .cpp) files.
}
To fix the problem:
//my_class.cpp
void my_class::my_function()
{
// Now in a .cpp file, so no multiple definition error
}
Or:
// my_class.hpp
inline void my_class::my_function()
{
// Specified function as inline, so okay - note: back in header file!
// The very first example has an implicit `inline` specifier
}
Reason 3 You want to save space, again, but this time you are working with a template class:
If we are working with template classes, then we cannot move the implementation to a source file (.cpp file). That's not currently allowed by (I assume) either the standard or by current compilers. Unlike the first example of Reason 2, above, we are allowed to place the implementation in the header file. According to this question the reason is that template class methods also have implied inline specifiers. Is that correct? (It seems to make sense.) But nobody seemed to know on the question I have just referenced!
So, are the two examples below identical?
// some_header_file.hpp
#pragma once
// template class declaration goes here
class some_class
{
// Some code
};
// Example 1: NO INLINE SPECIFIER
template<typename T>
void some_class::class_method()
{
// Some code
}
// Example 2: INLINE specifier used
template<typename T>
inline void some_class::class_method()
{
// Some code
}
If you have a template class header file, which is becoming huge due to all the functions you have, then I believe you are allowed to move the function definitions to another header file (usually a .tpp file?) and then #include file.tpp at the end of your header file containing the class declaration. You must NOT include this file anywhere else, however, hence the .tpp rather than .hpp.
I assume you could also do this with the inline methods of a regular class? Is that allowed also?
Question Time
So I have made some statements above, most of which relate to the structuring of source files. I think everything I said was correct, because I did some basic research and "found out some stuff", but this is a question and so I don't know for sure.
What this boils down to, is how you would organize code within files. I think I have figured out a structure which will always work.
Here is what I have come up with. (This is my class code file organization/structure standard, if you like. Don't know if it will be very useful yet, that's the point of asking.)
1: Declare the class (template or otherwise) in a .hpp file, including all methods, friend functions and data.
2: At the bottom of the .hpp file, #include a .tpp file containing the implementation of any inline methods. Create the .tpp file and ensure all methods are specified to be inline.
3: All other members (non-inline functions, friend functions and static data) should be defined in a .cpp file, which #includes the .hpp file at the top to prevent errors like "class ABC has not been declared". Since everything in this file will have external linkage, the program will link correctly.
Do standards like this exist in industry? Will the standard I came up with work in all cases?
Your three points sound about right. That's the standard way to do things (although I've not seen .tpp extension before, usually it's .inl), although personally I just put inline functions at the bottom of header files rather than in a separate file.
Here is how I arrange my files. I omit the forward declare file for simple classes.
myclass-fwd.h
#pragma once
namespace NS
{
class MyClass;
}
myclass.h
#pragma once
#include "headers-needed-by-header"
#include "myclass-fwd.h"
namespace NS
{
class MyClass
{
..
};
}
myclass.cpp
#include "headers-needed-by-source"
#include "myclass.h"
namespace
{
void LocalFunc();
}
NS::MyClass::...
Replace pragma with header guards according to preference..
The reason for this approach is to reduce header dependencies, which slow down compile times in large projects. If you didn't know, you can forward declare a class to use as a pointer or reference. The full declaration is only needed when you construct, create or use members of the class.
This means another class which uses the class (takes parameters by pointer/reference) only has to include the fwd header in its own header. The full header is then included in the second class's source file. This greatly reduces the amount of unneeded rubbish you get when pulling in a big header, which pulls in another big header, which pulls in another...
The next tip is the unnamed namespace (sometimes called anonymous namespace). This can only appear in a source file and it is like a hidden namespace only visible to that file. You can place local functions, classes etc here which are only used by the the source file. This prevents name clashes if you create something with the same name in two different files. (Two local function F for example, may give linker errors).
The main reason to separate interface from implementation is so that you don't have to recompile all of your code when something in the implementation changes; you only have to recompile the source files that changed.
As for "Declare the class (template or otherwise)", a template is not a class. A template is a pattern for creating classes. More important, though, you define a class or a template in a header. The class definition includes declarations of its member functions, and non-inine member functions are defined in one or more source files. Inline member functions and all template functions should be defined in the header, by whatever combination of direct definitions and #include directives you prefer.
Do standards like this exist in industry?
Yes. Then again, coding standards that are rather different from the ones you expressed can also be found in industry. You are talking about coding standards, after all, and coding standards range from good to bad to ugly.
Will the standard I came up with work in all cases?
Absolutely not. For example,
template <typename T> class Foo {
public:
void some_method (T& arg);
...
};
Here, the definition of class template Foo doesn't know a thing about that template parameter T. What if, for some class template, the definitions of the methods vary depending on the template parameters? Your rule #2 just doesn't work here.
Another example: What if the corresponding source file is huge, a thousand lines long or longer? At times it makes sense to provide the implementation in multiple source files. Some standards go to the extreme of dictating one function per file (personal opinion: Yech!).
At the other extreme of a thousand-plus line long source file is a class that has no source files. The entire implementation is in the header. There's a lot to be said for header-only implementations. If nothing else, it simplifies, sometimes significantly, the linking problem.
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?
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.
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..
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.