Connecting Tech Pros Worldwide Help | Site Map

const and folding

  #1  
Old December 7th, 2006, 02:45 AM
Adrian
Guest
 
Posts: n/a
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!
  #2  
Old December 7th, 2006, 03:05 AM
Joseph Paterson
Guest
 
Posts: n/a

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.

  #3  
Old December 7th, 2006, 03:35 AM
Salt_Peter
Guest
 
Posts: n/a

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


Similar Threads
Thread Thread Starter Forum Replies Last Post
When to use const modifier? Leonardo Korndorfer answers 39 June 27th, 2008 08:39 PM
Surprising Problem codergem@gmail.com answers 7 July 27th, 2006 03:45 AM
Can I modify a constant variable through a pointer obtained from const_cast? CoolPint answers 20 July 22nd, 2005 05:53 PM
Is it constant folding at work Anshul Sawant answers 7 July 22nd, 2005 01:14 PM