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
Related
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.
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).
In OOP, you want to break apart a program into multiple classes.
In C#, you would do as such:
namespace a
{
public class ClassA
{
//Methods...that are defined and have code in them.
}
}
and to use that class, you just do "using namespace a;".
Say I want to create a class in C++, and define them, and put code in them.
class ClassA
{
public:
void methodA();
}
ClassA::methodA()
{
//implementation.
}
To access this implementation, you would just use #include "ClassA.h". I fully understand that, and then you have to implement that code again? That seems counterproductive as I like to spread my project over a lot of classes.
So what would be the proper procedure to implement ClassA and not re-implement all it's methods again?
You don't have to reimplement them in each CPP file, the C++ linker takes care of making sure the definitions get matched together.
All you need is:
A header:
#ifndef FOO_H
#define FOO_H
class Foo{
//Junk goes here
};
#endif
A cpp:
#include "foo.h"
//implementations for junk goes here
void Foo::junk(){
}
And then you can include foo.h. Each cpp will be compiled to a .o file. Than, those .o files are handed to the linker which can figure out where definitions are and piece together the code correctly.
C and C++ have a different way of doing things. As long as you have a declaration for a class, method, or external variable the compiler will happily compile and leave off the actual definition of the methods, classes, etc, for link time. This is simplifying things a lot, but basically the compiler will leave a hint to the linker in the object file, saying that the linker needs to insert the address of the method here.
So you just need to include the "ClassA.h" file and you can compile fine.
Because of this you see some different behavior in C and C++ than you would in C#. For example, in C or C++ it's perfectly fine to have two different items (methods, variables, etc) that are named the same in different files as long as neither one is visible outside the file. Whereas in C# you would have to use different namespaces or different names. Note - not that I'm saying this is good practice, it's just possible.
The .h header files contain the class specification. The corresponding .cpp files contain the implementation and are compiled to .o files. During development, you would include .h files to access the APIs provided by the class. During compilation/linking stage, you would include the .o files also along with your source files to form the final binary. You don't need to implement anything again, w.r.t to the class you are using.
What's the thoughts on allowing simple constructor/method definitions in header files in C++. Some classes I am creating are simple data objects that compose another object say, so they need there own constructor and get/set methods. However these are usually < 3-4 lines each with the constructors using init lists. Is it OK to just have .h for these classes.?
UPDATE::
What about where to store .h files, in a seperate directory from the cpp files?
I'd vote for only putting declarations in your header file. This will make the header file more clean (no implementation cluttering your view). The user can look upon the header file to view the interface, without being confronted with irrelevant implementation details.
Putting definitions (as opposed to declarations) in your header file can also cause linker errors (as mentioned by Captain Comic). Maybe not currently, but surely when you expand your code.
Besides, explicitly separating declaration from definition (lets forget templates and inline functions here) also works towards a more "perfect" model. The code will be completely modularized in separate source files. From my personal experiences this takes time and care, but is consistent and avoids linker errors etc.
Surely, if you're writing a quick application nobody else is going to see...nobody is there to criticize ;)
Go for it.
If you want a better response, elaborate on your problems, post code, etc.
I put .h files in the same directory as the .cpp files. They are coupled anyway, so why split them up?!
It's much easier for the IDE to locate the matching file when you want to jump between declaration (in foo.h) and definition (in foo.cpp).
Only for external headers, that is those headers that are used by external projects, I might create a separate folder.
One important thing you have to bear in mind is that it is the .cpp files that are compiled, not header files. So design carefully who will include you headers, otherwise you'll get linker errors.
I asked my professor this same question a few hours ago, when he advocated putting a few getters in a .h file, which was foreign to me as a C programmer.
He said that one purpose of the .h file was to give a quick overview of the class. If you've ever programmed in Java, you've probably built or read some huge classes, and locating a specific function can be a pain. A good text editor with folding capabilities or an IDE with an outline view can help you cope with the problem, but that's not always available. A one-line getter/setter or initializing constructor which will not slow a reader down is probably permissible.
Sometimes it all depends on the IDE or the environment in which you are developing the code. Usually
/source-tree
/bin -------> executables or lib or dlls
/h -------> headers
/source -------> source codes
/Makefile -------> The root make file
Now about the code structure, it depends on what you are developing. If some APIs for some data container, which will be used across different modules, It is something like, -
Header Files ------->
//ICoordinate.hpp
template <class T>
class ICoordinate
{
public:
virtual ~ICoordinate() {}
virtual void SetX(T ) = 0;
virtual void SetY(T ) = 0;
virtual T GetX(void) = 0;
};
// Co-ordinate system for ploting decimal points :-)
// class template specialization.
template <>
class ICoordinate<int>
{
public:
virtual ~ICoordinate() {}
void SetX(int );
void SetY(int );
private:
int x,y;
};
Source File --------->
// DecimalCoordinate.cpp
// Implementation for DecimalCoordinate
If you do not have problem with vtable lookup latency, you can always define with some pure virtual methods (just what i did here). There is post regarding the interface declaration.