470,831 Members | 1,407 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,831 developers. It's quick & easy.

const and folding

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!
Dec 7 '06 #1
2 1957
A message was posted about 5 minutes ago about global variables in
header files.
See
http://groups.google.com/group/comp....bf9f0e7fa85fdf

Joseph.

Dec 7 '06 #2

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
*/

Dec 7 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by Nuff Said | last post: by
reply views Thread by Jorge Godoy | last post: by
reply views Thread by Terry Hancock | last post: by
reply views Thread by Steve - DND | last post: by
14 posts views Thread by John Salerno | last post: by
39 posts views Thread by Leonardo Korndorfer | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.