C++, using external global variables in a namespace in multiple files [duplicate] - c++

This question already has answers here:
Defining Global Variables Between Two .cpp Files [duplicate]
(2 answers)
Global Varibles with using namespace
(2 answers)
How do I use extern to share variables between source files?
(19 answers)
Closed 17 days ago.
I would like to use external variables as parameters in several c++ files. How do I use a namespace with external vars? Without the namespace everything works.
crack_detection_opencv.cpp:-1: In function ‘void ProcessArgs(int, const char**)’:
fillSobelSearchSize = std::stoi(optarg);
reference to ‘fillSobelSearchSize’ is ambiguous
Shortened code:
void ProcessArgs(int argc, const char** argv_orig)
{
fillSobelSearchSize = std::stoi(optarg);
}
#pragma once
namespace cd
{
float contrastAlpha = 5.8f; //unused
float contrastBeta = -2.8f; //unused
float contrastAlpha2 = 5.6f; //unused
float contrastBeta2 = -2.8f; //unused
int fillSobelSearchSize = 20;
}
using namespace cd;
extern float contrastAlpha;// = 5.8f;
extern float contrastBeta;// = -2.8f;
extern float contrastAlpha2;// = 5.6f;
extern float contrastBeta2;// = -2.8f;
extern int fillSobelSearchSize;
I tried to use external global variables as parameters in several functions and wrap them in a namespace. Without the namespace it works fine, but there are compilation erros if I use a namespace.

Related

What effect does `static` have on a method in a namespace? [duplicate]

This question already has answers here:
Error in calling a static function in a namespace
(2 answers)
Static function vs Static member functions C++
(1 answer)
The static keyword and its various uses in C++
(9 answers)
Closed 6 months ago.
Does static mean anything on func2 in the context of a namespace? Both methods appear to be equivalent.
// MyHeader.h
namespace TestNameSpace
{
int func1() { return 1; }
static int func2() { return 2; }
}
// SomeFile.cpp
#include "MyHeader.h"
// ...
int test1 = TestNameSpace::func1(); // 1
int test2 = TestNameSpace::func2(); // 2
static functions (which are not member of classes) are only visible in the compilation unit they are defined in. Apart from that there should not be any difference between those two

Alternatives To Global Variables in C++

I need to set a variable in the main function and access it from a different function in the same file. I can not pass it to the function because it means changing the entire code structure, which is not an option. To avoid declaring a global variable I crated a namespace and I want to check if this is a good programming practice or is there a cleaner way to do it.
This is the code:
namespace mylocalnamespace{
int myglobalvar;
}
static void myFunc()
{
..... some code
operationX(mylocalnamespace::myglobalvar);
..... some code
}
int main(int argc, char **argv)
{
..... some code
mylocalnamespace::myglobalvar = atoi(argv[0]);
..... some code
}
Alternatives To Global Variables in C++
In the example, function argument is a good alternative to avoid a global variable:
static void myFunc(int mylocalvar)
{
..... some code
operationX(mylocalvar);
..... some code
}
int main(int argc, char **argv)
{
..... some code
mylocalvar = atoi(argv[0]);
..... some code
myFunc(mylocalvar);
}
I can not pass it to the function
Oh well, then you have to use a global variable.
Since you apparently use it in a function with internal linkage, you could improve slightly by using global with internal linkage as well. This way the global won't leak to other translation units. A handy way to achieve that is an anonymous namespace:
namespace {
int myglobalvar;
void myFunc() {
// ...
To avoid declaring a global variable I crated a namespace
Global variables are still global variables even if not in the global namespace.

const causes a linker error for external file [duplicate]

This question already has answers here:
Why does const imply internal linkage in C++, when it doesn't in C?
(7 answers)
Closed 1 year ago.
I have this cpp file which contains 2 arrays:
const float arr[123]={/*..*/};
const float ave[213]={/*..*/};
And in my main.cpp I have:
int main()
{
extern float arr[123];
float temp[123];
for(unsigned i=0; i<123;i++)
temp[i]=arr[i];
return 0;
}
When I build my project I got an error saying that there’s no definition for arr.
It’s a linker error.
What could be the problem?
Your const variable has internal linkage by default.
You need to declare it as extern as well to counteract that.

Definition or redeclaration not allowed inside a function [duplicate]

This question already has answers here:
How to define a const double inside a class's header file?
(3 answers)
Closed 7 years ago.
Something.h
1 class Something
2 {
3 private:
4 static int s_nIDGenerator;
5 int m_nID;
6 static const double fudgeFactor; // declaration - initializing here will be warning
7 public:
8 Something() { m_nID = s_nIDGenerator++; }
9
10 int GetID() const { return m_nID; }
11 };
foo.cpp
1 #include <iostream>
2 #include "Something.h"
3
4 // This works!
5 //const double Something::fudgeFactor = 1.57;
6
7 int main()
8 {
9 Something cFirst;
10 Something cSecond;
11 Something cThird;
12
13 const double Something::fudgeFactor = 3.14;
14
15 using namespace std;
16 cout << cFirst.GetID() << endl;
17 cout << cSecond.GetID() << endl;
18 cout << cThird.GetID() << endl;
19 return 0;
20 }
When trying to define the value of the static member variable of Class Something inside main, I encounter a compiler error as given below. Assigning a value outside the main() works fine. I understand that static member variables can be given a value only once, but why does assigning it outside a function versus inside a function matter?
$ clang++ foo.cpp
foo.cpp:13:29: error: definition or redeclaration of 'fudgeFactor' not allowed
inside a function
const double Something::fudgeFactor = 3.14;
~~~~~~~~~~~^
1 error generated.
You are not assigning the variable inside the function; you are defining it (and initializing it). You can't do that inside the function because of scope rules. The variable is declared in the global (namespace) scope; therefore it also has to be defined in the namespace scope. It is not a local variable.
By the way, for static const variables, recent C++ standards allow you to initialize them at the point of declaration (as in your .h file) but you still have to define them, but this time without the initializer:
const double Something::fudgeFactor;
Static data members of a class needs to have external linkage. By this rule, the static members must be defined in namespace scope.

Compilation failed, c++ program with static variable as private member variable [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
undefined reference to static member variable
What is an undefined reference/unresolved external symbol error and how do I fix it?
#include<iostream>
using namespace std;
class abc {
private:
static int a ;
public:
abc(int x) {
a = x;
}
void showData() {
cout<<"A = "<<a<<endl;
}
};
int main() {
abc a1(4);
abc a2(5);
a1.showData();
a2.showData();
return 0;
}
When I try to compile this function on Ubuntu with GCC compiler. I get the following error.
/tmp/ccCKK2YN.o: In function `main':
static1.cpp:(.text+0xb): undefined reference to `Something::s_nValue'
static1.cpp:(.text+0x14): undefined reference to `Something::s_nValue'
collect2: ld returned 1 exit status
Compilation failed.
Where as the following code runs fine
#include<iostream>
using namespace std;
class Something
{
public:
static int s_nValue;
};
int Something::s_nValue = 1;
int main()
{
Something cFirst;
cFirst.s_nValue = 2;
Something cSecond;
std::cout << cSecond.s_nValue;
return 0;
}
Is this because Static member variables needs to initialized explicitly before accessing them via objects.Why so ?
static int s_nValue; doesn't allocate any storage to store the int, it just declares it.
You allocate somewhere in memory to store the variable with:
int Something::a=0;
The declaration of a static data member in the member list of a class is not a definition. You must define the static member outside of the class declaration, in namespace scope.
See this thread.
In short, the static member needs to be initialized somewhere in a .cpp file so that the compiler allocates space for it. The declaration would look like this:
int abc::a = 0;
That happens because since static members are shared between all instances of a class, they need to be declared in one single place.
If you define the static variable inside the class declaration then each include to that file would have a definition to that variable (which is against to the static meaning).
Because of that you have to define the static members in the .cpp.