const vs #define

J

Jose Luis

Hi,

Given the code below:


<<<snip begin>>>

m3vmsa3.rraaupma /tmp > more p1.c p2.c defs.h

#include "defs.h"

int main()
{}

....skipping...

#include "defs.h"
....skipping...
#ifndef DEFS_H
#define DEFS_H

const char* STR1="Hello World";
const int i1=0;

#endif

<<<snip end>>>


If compiled:

m3vmsa3.rraaupma /tmp > aCC p1.c p2.c
p1.c:
p2.c:
/usr/ccs/bin/ld: Duplicate symbol "STR1" in files p1.o and p2.o
/usr/ccs/bin/ld: Found 1 duplicate symbol(s)


What is the best option for STR1: "static const" or "#define"?

Why is "i1" not a duplicate symbol?



Thanks in advance,
Jose Luis.
 
J

James Kanze

i1 is a const (by itself). STR1 is not a const, it's a
regular pointer to a const char. Make it
const char* const STR1 = ...
and it will be const.

Alternatively, he could just skip the pointer:

char const STR1[] = "Hello World" ;

Most of the time, this is probably closer to what is actually
wanted.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top