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

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

Related

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

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.

Basic C++ problem - Using variable within the class [duplicate]

This question already has answers here:
Call constructor inside a call to another constructor
(2 answers)
Most vexing parse C++11
(2 answers)
Closed 7 months ago.
I have problem with C++ class. Is there have any way to reuse variable in the same class in the header file?
I have try
PubSubClient mqttClient(this->secureClient);
PubSubClient mqttClient(mqtt.secureClient);
but fail. Why?
#ifndef __MQTT_H_
#define __MQTT_H_
#include "Arduino.h"
#include "WiFi.h"
#include "WiFiClientSecure.h"
#include "PubSubClient.h"
class MQTT
{
public:
bool initWiFi();
String macAddress6btye(void);
void callback(char *topic, byte *payload, unsigned int length);
bool mqttConnect();
bool mqttPublish(const String &endPoint, const String &payload);
int getStrength(uint8_t points);
private:
WiFiClientSecure secureClient;
PubSubClient mqttClient(this->secureClient);
};
#endif
The declaration
PubSubClient mqttClient(this->secureClient);
is treated as a function declaration. An invalid one.
If you want to initialize the member variable (using other member variables), you need to do it with a constructor initializer list:
class MQTT
{
public:
MQTT()
: secureClient(),
mqttClient(secureClient) // Initialization here
{
// Empty function body
}
// ...
WiFiClientSecure secureClient;
PubSubClient mqttClient; // No initialization here
};

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.

How to reference static member variables from a struct within another class [duplicate]

This question already has answers here:
Undefined reference to static class member
(9 answers)
Closed 8 years ago.
I'm trying to define some static constant strings in C++ and reference them from different files.
Here's how I have the information set up this far:
structClass.h
namespace test {
typedef struct customstructure{
static const std::string stringA;
} customstructure;
}
structClass.cpp
namespace test {
static const std::string customstructure::stringA = "This is String A";
}
Now I'm wondering how I would call this in a third file?
execute.cpp
void printStringA(){
printf("stringA is: %s", test::customstructure::stringA.c_str());
}
gives me a compile error that says:
undefined reference to 'test::customstructure::stringA'
In this code:
namespace test {
static const std::string customstructure::stringA = "This is String A";
}
remove the word static. In fact it is an error to have this, your compiler should give a more useful error message (although I suppose 'undefined reference' meets the requirements of "a diagnostic").
Standard reference: [class.static.data]#5 says that static data members have external linkage, however using the keyword static in the definition would specify internal linkage.

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.