#include inside function body or reduce its visibility - c++

Is there a way to reduce the scope of #include directive?
I mean for example to do something like this
void functionOneDirective()
{
#include "firstInstructionSet.h"
registerObject();
// cannot access instantiate()
}
void functionSecondDirective()
{
#include "secondInstructionSet.h"
instantiate();
// cannot access registerObject()
}
void main()
{
//cannot access instantiate() && registerObject()
}

It is not possible to restrict "includes" to a subset of the using file. It is always visible for anything following the include.
If you are interested in providing "different" views on certain functionality, consider using different namespaces to express these different "views".

#include directly inserts the file contents at the spot. So it depends on the contents of the header, but generally the answer is no. If it's a C header surrounding the inclusion with a namespace might work, but I'm not sure.

#include is resolved during compilation, you can't change it in the code. But you can use preprocessor directives to control which files are included :
#if defined(A) && A > 3
#include 'somefile.h'
#else
#include 'someotherfile.h'
#endif

A possible solution to your question (and the correct way to organize your source code) is to create a separate .c file for each function or group of related functions. For each .c file you also write a .h file that contains the declarations of the elements (types, constants, variables, functions) from the .c file that are published by that file.
The variables declared in the .h file need to be prefixed with the extern keyword (to let the compiler know they reside in a different .c file).
Then, let each .c file include only the .h files it needs (those that declare the functions/types/variables that are used in this .c file).
Example
File firstInstructionSet.h
typedef int number;
void registerObject();
File firstInstructionSet.c
void registerObject()
{
/* code to register the object here */
}
File oneDirective.h
void functionOneDirective();
File oneDirective.c
#include "firstInstructionSet.h"
void functionOneDirective()
{
registerObject();
// cannot access instantiate() because
// the symbol 'instantiate' is not known in this file
}
File secondDirective.h
extern int secondVar;
void functionSecondDirective();
File secondDirective.c
#include "secondInstructionSet.h"
int secondVar = 0;
void functionSecondDirective()
{
instantiate();
// cannot access registerObject() because
// the symbol 'registerObject' is not known in this file
}
File secondInstructionSet.h
void instantiate();
File secondInstructionSet.c
void instantiate()
{
/* code to instantiate here */
}
File main.c
#include "oneDirective.h"
#include "secondDirective.h"
void main()
{
// cannot access instantiate() && registerObject()
// because these symbols are not known in this file.
// but can access functionOneDirective() and functionSecondDirective()
// because the files that declare them are included (i.e. these
// symbols are known at this point
// it also can access variable "secondVar" and type "number"
}

Related

How to do Google test for function which are not a part of class?

Am performing Google test, Here am facing one challenge.
In my project some of the functions are not included in the header file, they are directly included in the source file. I can access the functions which are in header file by creating obj of the class but am not able to access which are only in source file.
Please guide me how to access these function.
Thanks in advance!.
Kiran JP
Declare them extern in your test code.
Example. Let's say you have a source file like this:
// Function declared and defined in .cpp file
void myFunction() {
// implementation
}
Then you could go ahead and do the following in your test code:
extern void myFunction();
TEST(MyTest) {
myFunction();
}
Unless the function was explicitly declared with internal linkage. Either by declaring it static or by declaring/defining it inside an anonymous namespace in C++11 or above.
You will need to add the declaration of those functions to a header file, either to your existing header files, or to a new header file.
For example, say you have this function in your class.cc file without any declaration in class.h file:
int SomeFunction(int a, int b){
//...
}
You should add the following line to a header file. Let's call it header.h:
// header.h
int SomeFunction(int a, int b);
Then modify your test file to include header.h:
#include "header.h"
TEST(SomeFunction, Test1) {
int c = SomeFunction(1,2);
}

error LNK2005: already defined on including a header file twice

I need to edit and access a few variables across multiple cpp files in a visual studio project. So I created a header file with a namespace containing all the variables I require as follows:
namespace windowdimension{
TCHAR openwindows[20][180];
int winnum = 0;
int windowleft = 0;
int windowright = 1360;
INT windowtop = 0;
INT windowbottom = 768;
LONG leftarray[20];
LONG rightarray[20];
LONG toparray[20];
LONG bottomarray[20];
}
However if I #include this header file in two source files, I get this linker error 2005 saying the parameter was already defined in the other obj.
On referring to other question of the same error, I got to know here that
a function definition can only appear once. Every .cpp file that #includes your .h file will generate yet another copy of the function.
But does that hold for namespace variables as well?
If so how do we ensure access to a particular variable across multiple source files?
You should never define global variables in a header file.
To be able to share, you need to declare them in a header file (using extern keyword), and define only once in a .cpp file.
Sure, never forget about include guards in every header file (#pragma once is pretty portable solution):
global.hpp
#pragma once
namespace global {
extern int variable;
}
global.cpp
namespace global {
int variable = 0;
}
Anyway, it is a very bad practice to use global variables.
You probably forgot to add an include guard:
Header.h
#ifndef HEADER_H
#define HEADER_H
namespace something {
}
#endif
Another option is to use #pragma once in the very beginning of your header file.

C++ I have a function used in all my headers

I have a function that is the same across all my header files and main.cpp if I define it in main.cpp will they all be able to use it once they are included or will they have a compiler issue?
Still new to this whole header file business. Thanks in advance.
In the header file (myfunction.h), you need to have only declaration of the function:
int foo(int param);
In the main.cpp (or any other cpp file - better choice would be myfunction.cpp - just make sure definition is included in exactly one file!) file, you need to have definition of the function:
int foo(int param)
{
return 1;
}
In all other source (cpp) files where you're using function foo, just include myfunction.h and use function:
#include "myfunction.h"
void someotherfunction()
{
std::cout << foo(1) << std::endl;
}
Compiler only needs to see declaration of the function before it is used. Linker will connect definition of the function with the places you've used the function. If you forget to write definition in main.cpp file, you will not get compiler, but a linker error. It may be worth of mentioning that compiler is compiling each cpp file separately, and linker's job is to combine all compiler object files and to produce final output file. On most setups, linker will be called automatically after compiling, so you may not be familiar with it.
If you include entire function definition in the header file, that definition will be compiled in each translation unit where header file is included, and you will get multiple symbol definition linker error, or something similar - that's why you need to include only declaration of the function inside header file. However, there are exceptions for this - for example, you may declare your function inline - other answers explain this approach.
So, now myfunction.h contains the function declaration:
#ifndef MY_FUNCTION_H
#define MY_FUNCITON_H
// declaration
int myfunction();
#end if
myfunction.cpp contains the function definition:
int myfunction()
{
return 4;
}
Now, in file1.cpp and in file2.cpp you want to use this function, so you're including myfunction.h:
// file1.cpp
#include "myfunction.h"
// somewhere in the file
void foo()
{
std::cout << myfunction();
}
... and in the second file:
// file2.cpp
#include "myfunction.h"
// somewhere in the file
void bar()
{
/// ...
std::cout << myfunction();
}
Header files in C and C++ are a language artifact. They are the consequence of the fact, that C and C++ can be implemented as a single-pass compiler. In contrast, Pascal - for example - has a two-pass compiler, that skips over unknown entities during the first pass, and fills in the missing bits in a second pass. Consequently, in C and C++ every type, object, and method must be declared before it can be used. This is the main responsibility of header files.
Header files are expanded into any file that includes them. In other words: The preprocessor replaces the statement #include "foo.h" with the contents of the file "foo.h". With this being the case you need to be careful to not violate the single definition rule: An entity must not be defined more than once.
To meet both requirements you have two options: Declare and define the function in the header, using the inline keyword, or declaring it in the header only, and defining it in another compilation unit.
The following code illustrates both solutions:
// foo.h
inline void foo() {
// Method is implemented in this header file.
// It is marked 'inline' to prevent linker errors
// concerning multiply defined symbols.
...
}
Delaration in header only, implementation in another compilation unit:
// foo.h
extern void foo();
// foo.cpp (or another compilation unit)
void foo() {
...
}
Regardless of which solution you go with, you can use foo() from any compilation unit. If you want to use it from "main.cpp" the code would look something like this:
// main.cpp
#include "foo.h"
int main() {
foo();
}
So you have a function which is used in all your header files, why don't you make a utility.h which keeps track of these types of functions and inline the functions in the .h ?
Declare the function prototype in a custom header file:
int add(int a, int b);
let say header file name is myfunction.h and include it wherever you need the function.
now you can define a function on another.cpp or main.cpp
int add(int a, int b){
return a+b;
}
include your custom header file like this:
#include "myfunction.h"
remember your main.cpp and other cpp files and the new header file should be in the same path.
If you have two files:
main.cpp
#include "func.h"
int main(){
hello();
std::cout<<" world!\n";
return 0;
}
& func.h
#ifndef FUNC_H
#define FUNC_H
#include <iostream>
void hello(void){
std::cout<<"hello";
}
#endif
iostreams objects and functions e.t.c will work fine from within main.cpp.
This posts answers sum up #ifndef pretty well if you would like to know more.

How to organize header/code files in C++ if I want only well-architectured workspace but not necessarily separated compilation?

I began to write my program in a single cpp-file but now I have too much code so I decided to separate it. But the problem is that I have many constants, includes and some other things that I want to have all in one place. Unfortunately, all of them are needed by dependent parts of code so I can't do it with usual include files.
What would help me?
(I write under Linux and compile with command-line)
(Sorry for my English :))
As Hristo said, you should generally write the definitions in header files and write the implementation in the source code files.
To answer your question however:
But the problem is that I have many constants, includes and some other things that I want to have all in one place.
What I've typically done is create a single file called something like "common.h" or "defs.h" (I took the idea from Doom...) and that file has many defines that you find you need throughout your entire program. If you are using constants, declare the constants in the header file like so:
extern const int MAX_SOMETHING;
extern const bool TRUTH_VALUE;
and make a complementary source file (defs.cpp or common.cpp) that defines these constants:
const int MAX_SOMETHING = 5;
const bool TRUTH_VALUE = true;
so now when you include the common/defs.h in other source files, the extern keyword will tell that source file that the definition is in another source file (its in the common/defs.cpp) so it will find the definition in there, and you can use it anywhere where you have included common/defs.cpp.
In most projects definitions are in header files and implementations are in source code files. However the implementations of template functions must be in the header files because they must be visible to all source files using them. Variables should be defined extern in header files and be declared in source files. Constants may also be declared in header files static.
Example:
Foo.h
#pragma once
class Foo{
public:
void bar();
template<class Type>
void increment(Type &a){
++a;
return;
}
};
extern Foo theFoo;
static const int five=5;
Foo.cpp
#include "Foo.h"
#include <iostream>
void Foo::bar(){
std::cout<<"Foo::bar called"<<std::endl;
return;
}
Foo theFoo;
Main.cpp
#include "Foo.h"
#include <iostream>
int main(){
theFoo.bar();
std::cout<<five<<std::endl;
return 0;
}

Good Practice, in including source files

I am using boost msm library (you don't need to know how it works) to code my statemachine, and i have a cpp source file organization question.
in the first source file (1.cpp) I define the statemachine, the event and the actions and the transition table, but I would like to define the state in another cpp file just because I would need to edit the states much more often then anything else in the statemachine.
Now what I did is that I wrote the states in another source file (2.cpp) and I included 2.cpp in 1.cpp
It compiles and everything, but its not clean at all, Id like to encapsulate this somehow..Any ideas?
Well typically you would include only .h files, i.e., the header files that declare types and the functions that you will implement in your associated .cpp file. You should not need to include an implementation file at all. Have you created any header files? Here is a basic example:
// Foo.h
class Foo {
// note that it is not defined here, only declared
public void some_function(int i);
};
// Foo.cpp
#include "Foo.h"
#include <iostream>
// implement the function here
void Foo::some_func(int i) {
std::cout << i;
}
Typically in C++ the definitions of classes and the function prototypes exist in header files (ending in .h or .hpp), with the implementation of functions existing in source files (ending in .cpp or .cxx). This allows you to expose an external interface so that other files can use the definitions used in the first file. You would make function prototypes and class declarations in your header file, and then include that header file in both cpp files.
In general, it is good practice to only include header files, and not include source files in other files.
If i were to write this from scratch (a finite state machine),
i will put following inside:
fsm.h:
struct fsm_rule {
/* state to which this rule belongs to */
int state;
/* new state */
int next;
/* is called when rule matches */
int (*fn)(int in, void *ctx);
};
struct fsm_state {
int nrules;
struct fsm_rule *rules;
};
struct fsm {
int nstates;
struct fsm_state *states;
};
and then inside fsm.c i will go ahead and implement required methods.
PS: Ofcouse fsm.c includes fsm.h