I've done this so many times, yet the reason why Visual Studio is complaining about this escapes me.
Manipulator.cpp:
#include "Manipulator.h"
Manipulator::Manipulator() {}
Manipulator::~Manipulator() {}
void proc(std::string p, int f, std::string c)
{
// switch-case p to c based on f:
return;
}
Manipulator.h: (void -proc- has a curly underscore, and that's what's driving me up the wall.)
#ifndef MANIPULATOR_H
#define MANIPULATOR_H
#include <string>
class Manipulator
{
private:
protected:
public:
Manipulator() ;
~Manipulator() ;
void proc(std::string, int, std::string);
// function definition for 'proc' not found.
};
#endif MANIPULATOR_H
main.cpp
#include "Manipulator.h"
...
int main()
{
...
Manipulator m;
...
m.proc(opdBMP, fxn, newBMP);
return 0;
}
What is it that VS wants so that I can get a move on? It is telling me that there are two linker errors: LNK2019 and LNK1120 (unresolved external). (I used to keep track of these kinds of errors but lost the file as a log with these.)
The compiler is correct in complaining, because the definition should be
void Manipulator::proc(std::string p, int f, std::string c) {
...
}
You just defined a free function instead of a member of Manipulator.
What is the best way to initialize a private, static data member in C++? I tried this in my header file, but it gives me weird linker errors:
class foo
{
private:
static int i;
};
int foo::i = 0;
I'm guessing this is because I can't initialize a private member from outside the class. So what's the best way to do this?
The class declaration should be in the header file (Or in the source file if not shared).
File: foo.h
class foo
{
private:
static int i;
};
But the initialization should be in source file.
File: foo.cpp
int foo::i = 0;
If the initialization is in the header file then each file that includes the header file will have a definition of the static member. Thus during the link phase you will get linker errors as the code to initialize the variable will be defined in multiple source files.
The initialisation of the static int i must be done outside of any function.
Note: Matt Curtis: points out that C++ allows the simplification of the above if the static member variable is of const integer type (bool, char, char8_t [since C++20], char16_t, char32_t, wchar_t, short, int, long, long long, or any implementation-defined extended integer types, including any signed, unsigned, and cv-qualified variants.). You can then declare and initialize the member variable directly inside the class declaration in the header file:
class foo
{
private:
static int const i = 42;
};
For a variable:
foo.h:
class foo
{
private:
static int i;
};
foo.cpp:
int foo::i = 0;
This is because there can only be one instance of foo::i in your program. It's sort of the equivalent of extern int i in a header file and int i in a source file.
For a constant you can put the value straight in the class declaration:
class foo
{
private:
static int i;
const static int a = 42;
};
Since C++17, static members may be defined in the header with the inline keyword.
http://en.cppreference.com/w/cpp/language/static
"A static data member may be declared inline. An inline static data member can be defined in the class definition and may specify a default member initializer. It does not need an out-of-class definition:"
struct X
{
inline static int n = 1;
};
For future viewers of this question, I want to point out that you should avoid what monkey0506 is suggesting.
Header files are for declarations.
Header files get compiled once for every .cpp file that directly or indirectly #includes them, and code outside of any function is run at program initialization, before main().
By putting: foo::i = VALUE; into the header, foo:i will be assigned the value VALUE (whatever that is) for every .cpp file, and these assignments will happen in an indeterminate order (determined by the linker) before main() is run.
What if we #define VALUE to be a different number in one of our .cpp files? It will compile fine and we will have no way of knowing which one wins until we run the program.
Never put executed code into a header for the same reason that you never #include a .cpp file.
Include guards (which I agree you should always use) protect you from something different: the same header being indirectly #included multiple times while compiling a single .cpp file.
With a Microsoft compiler[1], static variables that are not int-like can also be defined in a header file, but outside of the class declaration, using the Microsoft specific __declspec(selectany).
class A
{
static B b;
}
__declspec(selectany) A::b;
Note that I'm not saying this is good, I just say it can be done.
[1] These days, more compilers than MSC support __declspec(selectany) - at least gcc and clang. Maybe even more.
int foo::i = 0;
Is the correct syntax for initializing the variable, but it must go in the source file (.cpp) rather than in the header.
Because it is a static variable the compiler needs to create only one copy of it. You have to have a line "int foo:i" some where in your code to tell the compiler where to put it otherwise you get a link error. If that is in a header you will get a copy in every file that includes the header, so get multiply defined symbol errors from the linker.
If you want to initialize some compound type (f.e. string) you can do something like that:
class SomeClass {
static std::list<string> _list;
public:
static const std::list<string>& getList() {
struct Initializer {
Initializer() {
// Here you may want to put mutex
_list.push_back("FIRST");
_list.push_back("SECOND");
....
}
}
static Initializer ListInitializationGuard;
return _list;
}
};
As the ListInitializationGuard is a static variable inside SomeClass::getList() method it will be constructed only once, which means that constructor is called once. This will initialize _list variable to value you need. Any subsequent call to getList will simply return already initialized _list object.
Of course you have to access _list object always by calling getList() method.
C++11 static constructor pattern that works for multiple objects
One idiom was proposed at: https://stackoverflow.com/a/27088552/895245 but here goes a cleaner version that does not require creating a new method per member.
main.cpp
#include <cassert>
#include <vector>
// Normally on the .hpp file.
class MyClass {
public:
static std::vector<int> v, v2;
static struct StaticConstructor {
StaticConstructor() {
v.push_back(1);
v.push_back(2);
v2.push_back(3);
v2.push_back(4);
}
} _staticConstructor;
};
// Normally on the .cpp file.
std::vector<int> MyClass::v;
std::vector<int> MyClass::v2;
// Must come after every static member.
MyClass::StaticConstructor MyClass::_staticConstructor;
int main() {
assert(MyClass::v[0] == 1);
assert(MyClass::v[1] == 2);
assert(MyClass::v2[0] == 3);
assert(MyClass::v2[1] == 4);
}
GitHub upstream.
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
See also: static constructors in C++? I need to initialize private static objects
Tested on Ubuntu 19.04.
C++17 inline variable
Mentioned at: https://stackoverflow.com/a/45062055/895245 but here is a multifile runnable example to make it even clearer: How do inline variables work?
This awesome C++17 feature allow us to:
conveniently use just a single memory address for each constant
store it as a constexpr: How to declare constexpr extern?
do it in a single line from one header
main.cpp
#include <cassert>
#include "notmain.hpp"
int main() {
// Both files see the same memory address.
assert(¬main_i == notmain_func());
assert(notmain_i == 42);
}
notmain.hpp
#ifndef NOTMAIN_HPP
#define NOTMAIN_HPP
inline constexpr int notmain_i = 42;
const int* notmain_func();
#endif
notmain.cpp
#include "notmain.hpp"
const int* notmain_func() {
return ¬main_i;
}
Compile and run:
g++ -c -o notmain.o -std=c++17 -Wall -Wextra -pedantic notmain.cpp
g++ -c -o main.o -std=c++17 -Wall -Wextra -pedantic main.cpp
g++ -o main -std=c++17 -Wall -Wextra -pedantic main.o notmain.o
./main
GitHub upstream.
I don't have enough rep here to add this as a comment, but IMO it's good style to write your headers with #include guards anyway, which as noted by Paranaix a few hours ago would prevent a multiple-definition error. Unless you're already using a separate CPP file, it's not necessary to use one just to initialize static non-integral members.
#ifndef FOO_H
#define FOO_H
#include "bar.h"
class foo
{
private:
static bar i;
};
bar foo::i = VALUE;
#endif
I see no need to use a separate CPP file for this. Sure, you can, but there's no technical reason why you should have to.
You can also include the assignment in the header file if you use header guards. I have used this technique for a C++ library I have created. Another way to achieve the same result is to use static methods. For example...
class Foo
{
public:
int GetMyStatic() const
{
return *MyStatic();
}
private:
static int* MyStatic()
{
static int mStatic = 0;
return &mStatic;
}
}
The above code has the "bonus" of not requiring a CPP/source file. Again, a method I use for my C++ libraries.
The linker problem you encountered is probably caused by:
Providing both class and static member definition in header file,
Including this header in two or more source files.
This is a common problem for those who starts with C++. Static class member must be initialized in single translation unit i.e. in single source file.
Unfortunately, the static class member must be initialized outside of the class body. This complicates writing header-only code, and, therefore, I am using quite different approach. You can provide your static object through static or non-static class function for example:
class Foo
{
// int& getObjectInstance() const {
static int& getObjectInstance() {
static int object;
return object;
}
void func() {
int &object = getValueInstance();
object += 5;
}
};
I follow the idea from Karl. I like it and now I use it as well.
I've changed a little bit the notation and add some functionality
#include <stdio.h>
class Foo
{
public:
int GetMyStaticValue () const { return MyStatic(); }
int & GetMyStaticVar () { return MyStatic(); }
static bool isMyStatic (int & num) { return & num == & MyStatic(); }
private:
static int & MyStatic ()
{
static int mStatic = 7;
return mStatic;
}
};
int main (int, char **)
{
Foo obj;
printf ("mystatic value %d\n", obj.GetMyStaticValue());
obj.GetMyStaticVar () = 3;
printf ("mystatic value %d\n", obj.GetMyStaticValue());
int valMyS = obj.GetMyStaticVar ();
int & iPtr1 = obj.GetMyStaticVar ();
int & iPtr2 = valMyS;
printf ("is my static %d %d\n", Foo::isMyStatic(iPtr1), Foo::isMyStatic(iPtr2));
}
this outputs
mystatic value 7
mystatic value 3
is my static 1 0
Also working in privateStatic.cpp file :
#include <iostream>
using namespace std;
class A
{
private:
static int v;
};
int A::v = 10; // possible initializing
int main()
{
A a;
//cout << A::v << endl; // no access because of private scope
return 0;
}
// g++ privateStatic.cpp -o privateStatic && ./privateStatic
What about a set_default() method?
class foo
{
public:
static void set_default(int);
private:
static int i;
};
void foo::set_default(int x) {
i = x;
}
We would only have to use the set_default(int x) method and our static variable would be initialized.
This would not be in disagreement with the rest of the comments, actually it follows the same principle of initializing the variable in a global scope, but by using this method we make it explicit (and easy to see-understand) instead of having the definition of the variable hanging there.
One "old-school" way to define constants is to replace them by a enum:
class foo
{
private:
enum {i = 0}; // default type = int
enum: int64_t {HUGE = 1000000000000}; // may specify another type
};
This way doesn't require providing a definition, and avoids making the constant lvalue, which can save you some headaches, e.g. when you accidentally ODR-use it.
Here are all possibilities and errors in one simple example ...
#ifndef Foo_h
#define Foo_h
class Foo
{
static const int a = 42; // OK
static const int b {7}; // OK
//static int x = 42; // ISO C++ forbids in-class initialization of non-const static member 'Foo::x'
//static int y {7}; // ISO C++ forbids in-class initialization of non-const static member 'Foo::x'
static int x;
static int y;
int m = 42;
int n {7};
};
// Foo::x = 42; // error: 'int Foo::x' is private
int Foo::x = 42; // OK in Foo.h if included in only one *.cpp -> *.o file!
int Foo::y {7}; // OK
// int Foo::y {7}; // error: redefinition of 'int Foo::y'
// ONLY if the compiler can see both declarations at the same time it,
// OTHERWISE you get a linker error
#endif // Foo_h
But better place this in Foo.cpp. This way you can separately compile each file and link them later, otherwise Foo:x will be present in multiple object files and cause a linker error. ...
// Foo::x = 42; // error: 'int Foo::x' is private, bad if Foo::X is public!
int Foo::x = 42; // OK in Foo.h if included in only one *.cpp -> *.o file!
int Foo::y {7}; // OK
Does this serves your purpose?
//header file
struct MyStruct {
public:
const std::unordered_map<std::string, uint32_t> str_to_int{
{ "a", 1 },
{ "b", 2 },
...
{ "z", 26 }
};
const std::unordered_map<int , std::string> int_to_str{
{ 1, "a" },
{ 2, "b" },
...
{ 26, "z" }
};
std::string some_string = "justanotherstring";
uint32_t some_int = 42;
static MyStruct & Singleton() {
static MyStruct instance;
return instance;
}
private:
MyStruct() {};
};
//Usage in cpp file
int main(){
std::cout<<MyStruct::Singleton().some_string<<std::endl;
std::cout<<MyStruct::Singleton().some_int<<std::endl;
return 0;
}
I just wanted to mention something a little strange to me when I first encountered this.
I needed to initialize a private static data member in a template class.
in the .h or .hpp, it looks something like this to initialize a static data member of a template class:
template<typename T>
Type ClassName<T>::dataMemberName = initialValue;
I have defined some static functions in their own .h and .cpp files, so these may be called from elsewhere without need for instantiation:
functions.h
#pragma once
class functions {
public:
static const int addition(const int&, const int&);
static const int product(const int&, const int&);
};
functions.cpp
#include "functions.h"
const int functions::addition(const int& op1, const int& op2) {
return op1 + op2;
}
const int functions::product(const int& op1, const int& op2) {
return op1 * op2;
}
I have also created a section for program settings where I will define which of the functions to pick:
constants.h
#pragma once
const int modulus = 10;
extern const int(*operation)(const int&, const int&);
constants.cpp
#include "constants.h"
#include "functions.h"
const int(*operation)(const int&, const int&) = &functions::addition;
This code works as expected using the following sample:
main.cpp
#include <iostream>
#include "constants.h"
int main() {
int a = 7, b = 4;
std::cout << operation(a,b) % modulus << std::endl;
}
Problem is, now I would like to parametrize the functions addition and product using a non-type template, such as:
functions.h
#pragma once
class functions {
public:
template<const int&> static const int addition(const int&, const int&);
};
functions.cpp
#include "functions.h"
template<const int& sub> const int functions::addition(const int& op1, const int& op2) {
return op1 + op2 - sub;
}
The later code breaks, no matter how I try to adapt the other files. I have done everything I reasonably (and pointlessly) could imagine.
Any help on how to rewrite the code on constants.* will be very appreciated.
Templates are instantiated at compile time, and for that the definition must be known - you need to have the template definition in the header.
Even if you do that, you don't have an int as the parameter but a const int&.
That means that you need to instantiate it with an lvalue whose identity (i.e. location) can be determined at compile-time.
In turn, that means that the parameter must be a variable with external linkage - not a temporary or a local variable.
In other words:
extern int x;
void foo()
{
addition<1>(2,3); // Not good; not an lvalue
const int y = 1;
addition<y>(2,3); // Not good; no linkage
addition<x>(2,3); // Good
}
You probably want to use template<int sub> instead.
(Another side note: const references to primitive types are pointless. All they do is add overhead.)
Template definitions should either be visible to the compiler during instantiation, or explicitly instantiated. Since I highly doubt you can explicitly instantiate all your possible versions of integer template, you have put the defginitons into the header.
Than comes the problem of operations. Since it's a function pointer, it can only point to specific instance of your template - the one instantiated with specific integer template. Doubt it's usable at all.
I suggest to rethink your design.
I have a class, and within that class I define a struct. The struct has overloaded comparison operators so that it can be used with a map (with an int as the key).
Prior to messing with classes, I had the struct defined in a .cc file, and that file also contained a function which returned a map of this struct. It worked.
Now I want to have the struct defined in the class header, and the class should have a function which returns a map of structs.
Here is a simplified version of my code, which compiles with the same error as the full version. I don't understand the error, and would appreciate any help!
Cheers.
myclass.h:
#include <map>
class myclass {
public:
struct mystruct {
int i;
mystruct();
mystruct(int j);
bool operator==(const mystruct& rhs);
bool operator>(const mystruct& rhs);
bool operator<(const mystruct& rhs);
};
::std::map<int,mystruct> getStructMap();
};
myclass.cc:
#include <map>
#include "myclass.h"
myclass::mystruct::mystruct(int j) : i(j) {};
myclass::mystruct::mystruct() : i(-1) {};
bool ::myclass::mystruct::operator==(const ::myclass::mystruct& rhs) {return i==rhs.i; }
bool ::myclass::mystruct::operator>(const ::myclass::mystruct& rhs) {return i>rhs.i; }
bool ::myclass::mystruct::operator<(const ::myclass::mystruct& rhs) {return i<rhs.i; }
::std::map<int,::myclass::mystruct> ::myclass::getStructMap() {
::std::map<int,::myclass::mystruct> structMap;
for (int i=0;i<5;i++) structMap[i]=::myclass::mystruct(i);
return structMap;
}
myprogram.cc:
#include <iostream>
#include <map>
#include "myclass.h"
int main() {
myclass myobj;
::std::map<int,::myclass::mystruct> mymap;
mymap=myobj.getStructMap();
}
compile error:
> g++ -o myprogram myprogram.cc myclass.cc
myclass.cc:12: error: ‘class std::map<int, myclass::mystruct, std::less<int>,std::allocator<std::pair<const int, myclass::mystruct> > >::myclass’ has not been declared
myclass.cc:12: error: ISO C++ forbids declaration of ‘getStructMap’ with no type
myclass.cc: In function ‘int getStructMap()’:
myclass.cc:15: error: cannot convert ‘std::map<int, myclass::mystruct, std::less<int>, std::allocator<std::pair<const int, myclass::mystruct> > >’ to ‘int’ in return
Currently your code in parsed as
/*missing type*/ ::std::map<int,::myclass::mystruct>::myclass::getStructMap()
Thus, first error, map doesn't have myclass member (or subclasses, method, typedef, ...)
then the second error : no return type (so assuming int and thus the conversion error).
So to solve that, in myclass.cc, you may remove extra :: as follow:
::std::map<int,::myclass::mystruct> myclass::getStructMap() {
or add extra parenthesis:
::std::map<int,::myclass::mystruct> (::myclass::getStructMap()) {
I am new to c++ and SWIG
I am creating a python module using SWIG in windows environment.
After creating wrapper class (example_wrap.cxx). Started building using (python setup.py build_ext --inplace) for creating python module.
But I am getting *example_wrap.cxx(3090) : error C2062: type 'int' unexpected*
GradedComplex.h:
class GradedComplex
{
public:
typedef std::complex<double> dcomplex;
typedef Item<dcomplex> item_type;
typedef ItemComparator<dcomplex> comparator;
typedef std::set<item_type, comparator> grade_type;
private:
int n_;
std::vector<grade_type *> grade_;
std::vector<double> thre_;
public:
GradedComplex(int n, double *thre);
~GradedComplex();
void push(item_type item);
void avg(double *buf);
};
#endif
GradedComplex.cc
GradedComplex::GradedComplex(int n, double *thre)
{
n_ = n;
for (int i = 0; i < n_; ++i)
{
thre_.push_back(thre[i]);
grade_.push_back(new grade_type());
}
}
Then I build it for generating python module using SWIG.
Swig interface file (example.i)
GradedComplex(int n, double *thre);
I am not much expert in SWIG interface file
The wrapper class generated has large volume of code so i am pasting few.
code : example_wrap.cxx
3083: #define SWIG_FILE_WITH_INIT
3084: #include "Item.h"
3085: #include "GradedComplex.h"
3086: typedef std::complex<double> dcomplex;
3087: typedef Item<dcomplex> item_type;
3088: typedef ItemComparator<dcomplex> comparator;
3089: typedef std::set<item_type, comparator> grade_type;
3090: GradedComplex(int n, double *thre);
3091: void push(item_type item);
3092: void avg(double *buf);
3093: #include <string>
3094: #include <complex>
3095: #include <iostream>
3096: #if PY_VERSION_HEX >= 0x03020000
3097: # define SWIGPY_SLICE_ARG(obj) ((PyObject*) (obj))
3098: #else
3099: # define SWIGPY_SLICE_ARG(obj) ((PySliceObject*) (obj))
3100: #endif
The GradedComplex constructor:
GradedComplex::GradedComplex(int n, double *thre)
{
n_ = n;
for (int i = 0; i < n_; ++i)
{
thre_.push_back(thre[i]);
grade_.push_back(new grade_type());
}
}
Please suggest a to rectify this error
You apparently declared class GradedComplex somewhere in some header file (GradedComplex.h?)
Later you attempted to use this name in this line
GradedComplex(int n, double *thre);
To a human reader this line would probably look like an attempt to declare an independent function GradedComplex. Technically, it is legal to have a function with the same name as an existing class. However, since you specified no return type for this function, the compiler does not see this as a function declaration. The compiler thinks you are trying to declare an object of type GradedComplex with redundant parentheses around the declarator, as in
GradedComplex (a);
For this reason, the appearance of that int confuses it and leads to an error report about an unexpected int in line 3090.
What were you trying to do? If you were trying to define a constructor for GradedComplex, then you already know how to do it (you posted a correct definition yourself). What is the purpose of line 3090? Why did you write that line?
You can not have a function with no return type in c++. You should set a return type for the function GradedComplex. Constructors can not be declared like that.