Adrian wrote:
Hi,
In a header file I tried const char *someval="this is a test"; which
is included all over the place and I get linker errors about multiple
defines.
Why is this not folded when const char someval[]="this is a test"; is
and I get no linker errors?
Note that someval is not terminated and the compiler will ignore the
"..." if it finds someval[] to have already been defined. You'll
probably get a warning if you turn on some compiler options.
Headers should not hold definitions in its declarations. Headers should
also use include guards so as to prevent mutiple inclusions - maybe you
did, nobody else knows. Consider using std::string instead.
Perhaps you might use the following as a guide for const char* :
a) as a member
b) as a static str
c) as an external global str
____________
// A.h
#ifndef A_H_
#define A_H_ // <- include guard
class A {
static const char* p_stat; // static str
const char* p; // member str
public:
A(const char* p_);
/* member functions */
const char* const get_str() const;
static const char* const get_static_str();
};
#endif // include guard A_H_
____________
// A.cpp
#include "A.h"
const char* g_str = "global string";
const char* A::p_stat = "static string";
A::A(const char* p_) : p(p_)
{
}
const char* const A::get_str() const
{
return p;
}
const char* const A::get_static_str()
{
return p_stat;
}
____________
// test.cpp
#include <iostream>
#include <ostream>
#include "A.h"
extern const char* g_str;
int main()
{
A a("member string");
std::cout << a.get_str() << std::endl;
std::cout << a.get_static_str() << std::endl;
std::cout << g_str << std::endl;
}
/*
member string
static string
global string
*/