Connecting Tech Pros Worldwide Forums | Help | Site Map

const and folding

Adrian
Guest
 
Posts: n/a
#1: Dec 7 '06
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?




--

Adrian

Think you know a language? Post to comp.lang... and find out!

Joseph Paterson
Guest
 
Posts: n/a
#2: Dec 7 '06

re: const and folding


A message was posted about 5 minutes ago about global variables in
header files.
See
http://groups.google.com/group/comp....bf9f0e7fa85fdf

Joseph.

Salt_Peter
Guest
 
Posts: n/a
#3: Dec 7 '06

re: const and folding



Adrian wrote:
Quote:
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
*/

Closed Thread