Error: Invalid use of void - c++

I'm compiling C++ source (main.cpp) with a C header (hps_linux.h). The code in hps_linux.h is:
#ifndef HPS_LINUX_H_
#define HPS_LINUX_H_
#include <stdbool.h>
#include <stdint.h>
#include "socal/hps.h"
int fd_dev_mem = 0;
void *h2f_lw_axi_master = NULL;
size_t h2f_lw_axi_master_span = ALT_LWFPGASLVS_UB_ADDR -ALT_LWFPGASLVS_LB_ADDR + 1;
size_t h2f_lw_axi_master_ofst = ALT_LWFPGASLVS_OFST;
#endif
hps_linux.h includes hps.h, that has the next defines:
#define ALT_LWFPGASLVS_OFST 0xff200000
#define ALT_LWFPGASLVS_ADDR ALT_CAST(void *, (ALT_CAST(char *, ALT_HPS_ADDR) + ALT_LWFPGASLVS_OFST))
#define ALT_LWFPGASLVS_LB_ADDR ALT_LWFPGASLVS_ADDR
#define ALT_LWFPGASLVS_UB_ADDR ALT_CAST(void *, ((ALT_CAST(char *, ALT_LWFPGASLVS_ADDR) + 0x200000) - 1))
My main.cpp includes hps_linux.h . I'm compiling like this:
gcc -Wall -std=gnu99 hps_linux.c -o hps_linux.o
g++ -Wall -std=c++0x main.cpp -o main
And it throws the next error:
hps_linux.h: error: invalid use of 'void'
In line:
size_t h2f_lw_axi_master_span = ALT_LWFPGASLVS_UB_ADDR -ALT_LWFPGASLVS_LB_ADDR + 1;
When I compile it with a main written in C (main.c), it works.

Looking at the source code here, we have:
#ifdef __ASSEMBLY__
# define ALT_CAST(type, ptr) ptr // <-- not (ptr)???
#else
# define ALT_CAST(type, ptr) ((type) (ptr))
#endif /* __ASSEMBLY__ */
Now, we have:
size_t h2f_lw_axi_master_span = ALT_LWFPGASLVS_UB_ADDR - ALT_LWFPGASLVS_LB_ADDR + 1;
Partially expanding the macros, we have:
size_t h2f_lw_axi_master_span = ALT_CAST(void *, ALT_CAST(char *, ...)) - ALT_CAST(void *, ALT_CAST(char *, ...)) + 1;
Now, if __ASSEMBLY__ is set, this line is:
size_t h2f_lw_axi_master_span = ... - ... + 1;
Both ... expressions are integer, so this is OK. However, if __ASSEMBLY__ is not set, this line is:
size_t h2f_lw_axi_master_span = (void *) (...) - (void *) (...) + 1;
Subtracting two void pointers is not defined, so the compiler gives up.
Therefore, you need to ensure __ASSEMBLY__ is defined; one way would be:
g++ -Wall -D__ASSEMBLY__ -std=c++0x main.cpp -o main
However, this might cause problems as you should be relying on the earlier header files to set it correctly.
Update: A quick search of the git archive does not show __ASSEMBLY__ being set, and given the name it suggests it should be a compiler built-in...

Related

undefined reference to : what's wrong?

Im' trying to port a home made software from AIX to "Red Hat Enterprise Linux 7.8"
I'm facing "undefined reference to" errors at link time and, for now, I can't find where I screwed up.
The goal is to generate an executable from 2 homemade shared librairies (msi and atmi), some object previously compiled (MsiServices.o) and a C program (pingsrv.c).
Below is the command :
gcc -DWall -o bin/pingsrv -DUNIX -I. -g -DUNIX -D_THREAD_SAFE -D_LARGEFILE64_SOURCE -I/home/vgi/git/msi-tools/ping/server/target/msi/include/yaml-cpp -I/home/vgi/git/msi-tools/ping/server/target/msi/include/apr-1 -I/home/vgi/git/msi-tools/ping/server/target/msi/include/activemq-cpp-3.9.4 -I/home/vgi/git/msi-tools/ping/server/target/msi/include /tmp/MsiServices.o ./pingsrv.c -L/home/vgi/git/msi-tools/ping/server/target/msi/lib -lmsi -lactivemq-cpp -llog4cxx -latmi -lapr-1 -laprutil-1 -lexpat -lstdc++ -lyaml-cpp
Errors appears a link time:
/home/vgi/git/msi-tools/ping/server/target/msi/lib/libatmi.so: undefined reference to `Msi_tpreturn'
/home/vgi/git/msi-tools/ping/server/target/msi/lib/libatmi.so: undefined reference to `Msi_tpcall'
/home/vgi/git/msi-tools/ping/server/target/msi/lib/libmsi.so: undefined reference to `msi::service::optarg'
/home/vgi/git/msi-tools/ping/server/target/msi/lib/libatmi.so: undefined reference to `Msi_userlog'
Library atmi is written in C and is able to call some C++ instance methods by using wrappers:
...
typedef struct MsiScheduler MsiScheduler ;
extern void Msi_tpreturn(MsiScheduler *,int, long , char *, long, long);
extern void Msi_userlog(MsiScheduler *,char*) ;
extern int Msi_tpcall(MsiScheduler *,char *svc, char *idata, long ilen, char **odata, long *olen, long flags) ;
...
extern void tpreturn(int rval, long rcode, char * data, long len, long flags)
{
assert(vg_Consumer != NULL) ;
Msi_tpreturn(vg_Consumer,rval,rcode,data,len,flags) ;
}
Wrappers called by this library are defined in another library called msi. Wrappers are defined in a C++ source file (MsiScheduler.cpp):
void Msi_tpreturn(MsiScheduler * c,int ret,long code,char *data,long len,long flags)
{
TypedBuffer* buffer = NULL ;
if (data != NULL)
{
buffer = TypedBuffer::createBuffer(getType(data),data,len) ;
}
MsiReply * reply = MsiReply::createReply(ret,code,buffer) ;
c->tpreturn(reply) ;
if (data != NULL)
{
freebuf(data) ;
}
delete reply ;
}
int Msi_tpcall(MsiScheduler * c,char *svc, char *idata, long ilen, char **odata, long *olen, long flags)
{
...
}
void Msi_userlog(MsiScheduler *c ,char* str)
{
c->userlog(str) ;
}
header file (MsiScheduler.h) contains this fragment :
#ifdef __cplusplus
extern "C" {
#endif
#if defined(__STDC__) || defined(__cplusplus)
extern void Msi_tpreturn(MsiScheduler *,int, long , char *, long, long);
extern void Msi_userlog(MsiScheduler *,char*) ;
extern int Msi_tpcall(MsiScheduler *,char *svc, char *idata, long ilen, char **odata, long *olen, long flags) ;
#else
extern void Msi_tpreturn();
extern void Msi_userlog() ;
extern int Msi_tpcall() ;
#endif
#ifdef __cplusplus
}
#endif
Librairies are constructed like that:
g++ -g -fPIC -Wall -I/home/vgi/git/msi/msi-service/target/ext/include/apr-1 -I/home/vgi/git/msi/msi-service/target/ext/include/activemq-cpp-3.9.4 -I/home/vgi/git/msi/msi-service/target/ext/include/yaml-cpp -I/home/vgi/git/msi/msi-service/target/ext/include -I/home/vgi/git/msi/msi-service/target/ext/include -I../lib/inc -I./ -o MsiScheduler.o -c MsiScheduler.cpp
...
g++ -shared MsiUtil.o MsiConfig.o MsiInstrumentation.o MsiMetric.o MsiService.o MsiExceptions.o MsiCharsetConverter.o MsiTypes.o MsiMessage.o MsiMessageUtil.o MsiScheduler.o MsiServer.o -o libmsi.so
...
gcc -g -fPIC -Wall -I/home/vgi/git/msi/msi-service/target/ext/include/apr-1 -I/home/vgi/git/msi/msi-service/target/ext/include/activemq-cpp-3.9.4 -I/home/vgi/git/msi/msi-service/target/ext/include/yaml-cpp -I/home/vgi/git/msi/msi-service/target/ext/include -I/home/vgi/git/msi/msi-service/target/ext/include -I../lib/inc -I./ -o atmi.o -c atmi.c
gcc -shared atmi.o memmngt.o -o libatmi.so
FYI, everything compile and link well on AIX OS (with xlc,xlC commands).
I also tried to change librairies order for linking command, without success.
I guess there is something specific to linux/gcc but I haven't found it yet.
libmsi.so:0000000000034f20 T _Z10Msi_tpcallPN3msi7service12MsiSchedulerEPcS3_lPS3_Pll
libmsi.so:0000000000035138 T _Z11Msi_userlogPN3msi7service12MsiSchedulerEPc
libmsi.so:0000000000034e55 T _Z12Msi_tpreturnPN3msi7service12MsiSchedulerEilPcll
libatmi.so: U Msi_tpcall
libatmi.so: U Msi_tpreturn
libatmi.so: U Msi_userlog
In your nm output, the T's mean that the symbol on the right is defined in libmsi.so, and the U's mean that the symbol on the right is needed by libatmi.so. But obviously, the names of these symbols don't match up. The names in libmsi.so have the C++ mangling which helps keep overloaded functions separate.
This means the extern "C" did not apply to the function definitions when compiling MsiScheduler.cpp. Make sure it includes MsiScheduler.h, and that part of the header is not skipped by any #if. If that's not the issue, double check that the function parameter types are exactly the same in the MsiScheduler.h declarations and MsiScheduler.cpp definitions, though they seem to be.
When you're compiling pingsrv.c you try to link msi with -l. Have you put libmsi.so in the library path so that -l can find it?

use of undeclared identifier 'temp'

The below c++ code gives me error use of undeclared identifier 'temp'
/home/test/include/memory.h
#ifndef MEMORY_H
#define MEMORY_H
#if __ENABLE_MEMORY
__device__ int temp = 50;
extern "C" inline __device__ void* memory(){
...
temp = temp + 100;
...
}
#endif
#endif
/home/test/include/internal_memory.h
#ifndef INTERNAL_MEMORY_H
#define INTERNAL_MEMORY_H
#ifndef __ENABLE_MEMORY
#define __ENABLE_MEMORY 1
#endif
#if __ENABLE_MEMORY
extern "C" __device__ void* memory();
static inline __device__ void* call_memory(){ return memory();}
#endif
#include <memory.h>
#endif
/home/test/main.cpp
#include "internal_memory.h"
..
.
.
void show(){
std::cout << "temp is: " << temp << std::endl;
}
.
.
.
I m compiling the code with clang++ version 11.0.0.
clang --version looks as follows:
clang version 11.0.0
Target: x86_64-unknown-linux-gnu
Thread model: posix
InstalledDir: /opt/rocm/llvm/bin
Im compiling the code as below.
/opt/rocm/llvm/bin/clang++ -DDEBUG -D__x86_64__ -I/home/test/include -I/home/test -g -fPIC -std=c++14 -o main.o -c main.cpp
what am i missing here.
Function memory has the __device__ qualifier (I suppose you are compiling a CUDA program).
memory refers to temp, which is a global variable in host memory. You probably want __device__ int temp = 50;
To query temp, you would need to copy its value back to the host. Along the lines of
int host;
cudaMemcpy(&host, &temp, sizeof(int), cudaMemcpyDeviceToHost);

Clang: error: invalid use of non-static data member

Is this gcc being overly nice and doing what the dev thinks it will do or is clang being overly fussy about something. Am I missing some subtle rule in the standard where clang is actually correct in complaining about this
Or should I use the second bit of code which is basically the how offsetof works
[adrian#localhost ~]$ g++ -Wall -pedantic -ansi a.cc
[adrian#localhost ~]$ a.out
50
[adrian#localhost ~]$ cat a.cc
#include <iostream>
struct Foo
{
char name[50];
};
int main(int argc, char *argv[])
{
std::cout << sizeof(Foo::name) << std::endl;
return 0;
}
[adrian#localhost ~]$ clang++ a.cc
a.cc:10:29: error: invalid use of non-static data member 'name'
std::cout << sizeof(Foo::name) << std::endl;
~~~~~^~~~
1 error generated.
[adrian#localhost ~]$ g++ -Wall -pedantic -ansi b.cc
[adrian#localhost ~]$ a.out
50
[adrian#localhost ~]$ cat b.cc
#include <iostream>
struct Foo
{
char name[50];
};
int main(int argc, char *argv[])
{
std::cout << sizeof(static_cast<Foo*>(0)->name) << std::endl;
return 0;
}
[adrian#localhost ~]$ clang++ b.cc
[adrian#localhost ~]$ a.out
50
I found adding -std=c++11 stops it complaining. GCC is fine
with it in either version.
Modern GCC versions allow this even in -std=c++98 mode. However, older versions, like GCC 3.3.6 of mine, do complain and refuse to compile.
So now I wonder which part of C++98 I am violating with this code.
Wikipedia explicitly states that such a feature was added in C++11, and refers to N2253, which says that the syntax was not considered invalid by the C++98 standard initially, but then intentionally clarified to disallow this (I have no idea how non-static member fields are any different from other variables with regard to their data type). Some time later they decided to make this syntax valid, but not until C++11.
The very same document mentions an ugly workaround, which can also be seen throughout the web:
sizeof(((Class*) 0)->Field)
It looks like simply using 0, NULL or nullptr may trigger compiler warnings for possible dereference of a null pointer (despite the fact that sizeof never evaluates its argument), so an arbitrary non-zero value might be used instead, although it will look like a counter-intuitive “magic constant”. Therefore, in my C++ graceful degradation layer I use:
#if __cplusplus >= 201103L
#define CXX_MODERN 2011
#else
#define CXX_LEGACY 1998
#endif
#ifdef CXX_MODERN
#define CXX_FEATURE_SIZEOF_NONSTATIC
#define CxxSizeOf(TYPE, FIELD) (sizeof TYPE::FIELD)
#else
// Use of `nullptr` may trigger warnings.
#define CxxSizeOf(TYPE, FIELD) (sizeof (reinterpret_cast<const TYPE*>(1234)->FIELD))
#endif
Usage examples:
// On block level:
class SomeHeader {
public:
uint16_t Flags;
static CxxConstExpr size_t FixedSize =
#ifdef CXX_FEATURE_SIZEOF_NONSTATIC
(sizeof Flags)
#else
sizeof(uint16_t)
#endif
;
}; // end class SomeHeader
// Inside a function:
void Foo(void) {
size_t nSize = CxxSizeOf(SomeHeader, Flags);
} // end function Foo(void)
By the way, note the syntax difference for sizeof(Type) and sizeof Expression, as they are formally not the same, even if sizeof(Expression) works — as long as sizeof (Expression) is valid. So, the most correct and portable form would be sizeof(decltype(Expression)), but unfortunately it was made available only in C++11; some compliers have provided typeof(Expression) for a long time, but this never was a standard extension.

Differentiate String Literal from Char Array

I want to write some function that takes a string literal - and only a string literal:
template <size_t N>
void foo(const char (&str)[N]);
Unfortunately, that is too expansive and will match any array of char - whether or not it's a true string literal. While it's impossible to tell the difference between these at compile-time - without having to resort to requiring the caller to wrap the literal/array - at run-time, the two arrays will be in entirely different places in memory:
foo("Hello"); // at 0x400f81
const char msg[] = {'1', '2', '3'};
foo(msg); // at 0x7fff3552767f
Is there a way to know where in memory the string data could live so that I could at least assert that the function takes a string literal only? (Using gcc 4.7.3, but really a solution for any compiler would be great).
You seem to assume that a necessary trait of a "true string literal"
is that the compiler bakes it into the static storage of the executable.
This is not actually true. The C and C++ standards guarantee us that
a string literal shall have static storage duration, so it must exist for the
life of the program, but if a compiler can arrange this without placing
the literal in static storage, it is free to do so, and some compilers sometimes
do.
However, it's clear that the property you want to test, for a given string
literal, is whether it is in fact in static storage. And since it need not
be in static storage, as far as the language standards guarantee, there
can't be any solution of your problem founded solely on portable C/C++.
Whether a given string literal is in fact in static storage is the question
of whether the address of the string literal lies within one of the
address ranges that get assigned to linkage sections that qualify as
static storage, in the nomenclature of your particular toolchain, when
your program is built by that toolchain.
So the solution I suggest is that you enable your program to know the
address ranges of those of its own linkage sections that qualify as
static storage, and then it can test whether a given string literal
is in static storage by obvious code.
Here is an illustration of this solution for a toy C++ project, prog
built with the GNU/Linux x86_64 toolchain (C++98 or better will do, and the
approach is only slightly more fiddly for C). In this setting, we link in ELF
format, and the linkage sections we will deem static storage are .bss (0-initialized static data), .rodata
(read-only static static) and .data (read/write static data).
Here are our source files:
section_bounds.h
#ifndef SECTION_BOUNDS_H
#define SECTION_BOUNDS_H
// Export delimiting values for our `.bss`, `.rodata` and `.data` sections
extern unsigned long const section_bss_start;
extern unsigned long const section_bss_size;
extern unsigned long const section_bss_end;
extern unsigned long const section_rodata_start;
extern unsigned long const section_rodata_size;
extern unsigned long const section_rodata_end;
extern unsigned long const section_data_start;
extern unsigned long const section_data_size;
extern unsigned long const section_data_end;
#endif
section_bounds.cpp
// Assign either placeholder or pre-defined values to
// the section delimiting globals.
#ifndef BSS_START
#define BSS_START 0x0
#endif
#ifndef BSS_SIZE
#define BSS_SIZE 0xffff
#endif
#ifndef RODATA_START
#define RODATA_START 0x0
#endif
#ifndef RODATA_SIZE
#define RODATA_SIZE 0xffff
#endif
#ifndef DATA_START
#define DATA_START 0x0
#endif
#ifndef DATA_SIZE
#define DATA_SIZE 0xffff
#endif
extern unsigned long const
section_bss_start = BSS_START;
extern unsigned long const section_bss_size = BSS_SIZE;
extern unsigned long const
section_bss_end = section_bss_start + section_bss_size;
extern unsigned long const
section_rodata_start = RODATA_START;
extern unsigned long const
section_rodata_size = RODATA_SIZE;
extern unsigned long const
section_rodata_end = section_rodata_start + section_rodata_size;
extern unsigned long const
section_data_start = DATA_START;
extern unsigned long const
section_data_size = DATA_SIZE;
extern unsigned long const
section_data_end = section_data_start + section_data_size;
cstr_storage_triage.h
#ifndef CSTR_STORAGE_TRIAGE_H
#define CSTR_STORAGE_TRIAGE_H
// Classify the storage type addressed by `s` and print it on `cout`
extern void cstr_storage_triage(const char *s);
#endif
cstr_storage_triage.cpp
#include "cstr_storage_triage.h"
#include "section_bounds.h"
#include <iostream>
using namespace std;
void cstr_storage_triage(const char *s)
{
unsigned long addr = (unsigned long)s;
cout << "When s = " << (void*)s << " -> \"" << s << '\"' << endl;
if (addr >= section_bss_start && addr < section_bss_end) {
cout << "then s is in static 0-initialized data\n";
} else if (addr >= section_rodata_start && addr < section_rodata_end) {
cout << "then s is in static read-only data\n";
} else if (addr >= section_data_start && addr < section_data_end){
cout << "then s is in static read/write data\n";
} else {
cout << "then s is on the stack/heap\n";
}
}
main.cpp
// Demonstrate storage classification of various arrays of char
#include "cstr_storage_triage.h"
static char in_bss[1];
static char const * in_rodata = "In static read-only data";
static char in_rwdata[] = "In static read/write data";
int main()
{
char on_stack[] = "On stack";
cstr_storage_triage(in_bss);
cstr_storage_triage(in_rodata);
cstr_storage_triage(in_rwdata);
cstr_storage_triage(on_stack);
cstr_storage_triage("Where am I?");
return 0;
}
Here is our makefile:
.PHONY: all clean
SRCS = main.cpp cstr_storage_triage.cpp section_bounds.cpp
OBJS = $(SRCS:.cpp=.o)
TARG = prog
MAP_FILE = $(TARG).map
ifdef AGAIN
BSS_BOUNDS := $(shell grep -m 1 '^\.bss ' $(MAP_FILE))
BSS_START := $(word 2,$(BSS_BOUNDS))
BSS_SIZE := $(word 3,$(BSS_BOUNDS))
RODATA_BOUNDS := $(shell grep -m 1 '^\.rodata ' $(MAP_FILE))
RODATA_START := $(word 2,$(RODATA_BOUNDS))
RODATA_SIZE := $(word 3,$(RODATA_BOUNDS))
DATA_BOUNDS := $(shell grep -m 1 '^\.data ' $(MAP_FILE))
DATA_START := $(word 2,$(DATA_BOUNDS))
DATA_SIZE := $(word 3,$(DATA_BOUNDS))
CPPFLAGS += \
-DBSS_START=$(BSS_START) \
-DBSS_SIZE=$(BSS_SIZE) \
-DRODATA_START=$(RODATA_START) \
-DRODATA_SIZE=$(RODATA_SIZE) \
-DDATA_START=$(DATA_START) \
-DDATA_SIZE=$(DATA_SIZE)
endif
all: $(TARG)
clean:
rm -f $(OBJS) $(MAP_FILE) $(TARG)
ifndef AGAIN
$(MAP_FILE): $(OBJS)
g++ -o $(TARG) $(CXXFLAGS) -Wl,-Map=$# $(OBJS) $(LDLIBS)
touch section_bounds.cpp
$(TARG): $(MAP_FILE)
$(MAKE) AGAIN=1
else
$(TARG): $(OBJS)
g++ -o $# $(CXXFLAGS) $(OBJS) $(LDLIBS)
endif
Here is what make looks like:
$ make
g++ -c -o main.o main.cpp
g++ -c -o cstr_storage_triage.o cstr_storage_triage.cpp
g++ -c -o section_bounds.o section_bounds.cpp
g++ -o prog -Wl,-Map=prog.map main.o cstr_storage_triage.o section_bounds.o
touch section_bounds.cpp
make AGAIN=1
make[1]: Entering directory `/home/imk/develop/SO/string_lit_only'
g++ -DBSS_START=0x00000000006020c0 -DBSS_SIZE=0x118 -DRODATA_START=0x0000000000400bf0
-DRODATA_SIZE=0x120 -DDATA_START=0x0000000000602070 -DDATA_SIZE=0x3a
-c -o section_bounds.o section_bounds.cpp
g++ -o prog main.o cstr_storage_triage.o section_bounds.o
And lastly, what prog does:
$ ./prog
When s = 0x6021d1 -> ""
then s is in static 0-initialized data
When s = 0x400bf4 -> "In static read-only data"
then s is in static read-only data
When s = 0x602090 -> "In static read/write data"
then s is in static read/write data
When s = 0x7fffa1b053a0 -> "On stack"
then s is on the stack/heap
When s = 0x400c0d -> "Where am I?"
then s is in static read-only data
If it's obvious how this works, you need read no further.
The program will compile and link even before we know the addresses and
sizes of its static storage sections. It would need too, wouldn't it!? In
that case, the global section_* variables that ought to hold these values
all get built with place-holder values.
When make is run, the recipes:
$(TARG): $(MAP_FILE)
$(MAKE) AGAIN=1
and
$(MAP_FILE): $(OBJS)
g++ -o $(TARG) $(CXXFLAGS) -Wl,-Map=$# $(OBJS) $(LDLIBS)
touch section_bounds.cpp
are operative, because AGAIN is undefined. They tell make that in order
to build prog it must first build the linker map file of prog, as per
the second recipe, and then re-timestamp section_bounds.cpp. After that,
make is to call itself again, with AGAIN defined = 1.
Excecuting the makefile again, with AGAIN defined, make now finds that it
must compute all the variables:
BSS_BOUNDS
BSS_START
BSS_SIZE
RODATA_BOUNDS
RODATA_START
RODATA_SIZE
DATA_BOUNDS
DATA_START
DATA_SIZE
For each static storage section S, it computes S_BOUNDS by grepping
the linker map file for the line that reports the address and size of S.
From that line, it assigns the 2nd word ( = the section address) to S_START,
and the 3rd word ( = the size of the section) to S_SIZE. All the section
delimiting values are then appended, via -D options to the CPPFLAGS
that will automatically be passed to compilations.
Because AGAIN is defined, the operative recipe for $(TARG) is now the customary:
$(TARG): $(OBJS)
g++ -o $# $(CXXFLAGS) $(OBJS) $(LDLIBS)
But we touched section_bounds.cpp in the parent make; so it has to be
recompiled, and therefore prog has to be relinked. This time, when
section_bounds.cpp is compiled, all the section-delimiting macros:
BSS_START
BSS_SIZE
RODATA_START
RODATA_SIZE
DATA_START
DATA_SIZE
will have pre-defined values and will not assume their place-holder values.
And those predefined values will be correct because the second linkage
adds no symbols to the linkage and removes none, and does not alter the
size or storage class of any symbol. It just assigns different values to
symbols that were present in the first linkage. Consequently, the
addresses and sizes of the static storage sections will be unaltered and are now known to your program.
Depending on what exactly you want, this may or may not work for you:
#include <cstdlib>
template <size_t N>
void foo(const char (&str)[N]) {}
template <char> struct check_literal {};
#define foo(arg) foo((check_literal<arg[0]>(),arg))
int main()
{
// This compiles
foo("abc");
// This does not
static const char abc[] = "abc";
foo(abc);
}
This works with g++ and clang++ in -std=c++11 mode only.
You can use user-defined literals, that by definitions can only be applied to literals:
#include <iostream>
struct literal_wrapper
{
const char* const ptr;
private:
constexpr literal_wrapper(const char* p) : ptr(p) {}
friend constexpr literal_wrapper operator "" _lw(const char* p, std::size_t);
};
constexpr literal_wrapper operator "" _lw(const char* p, std::size_t){ return literal_wrapper(p); }
literal_wrapper f()
{
std::cout << "f()" << std::endl;
return "test"_lw;
}
void foo(const literal_wrapper& lw)
{
std::cout << "foo:" << lw.ptr << " " << static_cast<const void*>(lw.ptr) << std::endl;
}
int main()
{
auto x1 = f(), x2 = f(), x3 = f();
const void* p1 = x1.ptr;
const void* p2 = x2.ptr;
const void* p3 = x3.ptr;
std::cout << x1.ptr << " " << p1 << " " << p2 << " " << p3 << std::endl;
foo(x1);
foo(x2);
foo("test"_lw);
foo("test2"_lw);
}

compilation error about exceptions

I met some compilation error but do not know what the problem is. The code seems not use exception, but the error is about it.
//in misc.h:
char *basename(char *name); // line 94
// in misc.cc:
char *basename(char *name) { // line 12
char *result = name;
while(*name) {
if(*name == '/') result = name + 1;
name++;
}
return result;
}
Compilation error
g++ -pipe -W -Wall -fopenmp -ggdb3 -O2 -c -o misc.o ../../src/misc.cc
../../src/misc.cc: In function ‘char* basename(char*)’:
../../src/misc.cc:12: error: declaration of ‘char* basename(char*)’ throws different exceptions
../../src/misc.h:94: error: from previous declaration ‘char* basename(char*) throw ()’
make: *** [misc.o] Error 1
Does someone have some clue? Thanks and regards!
EDIT:
Files included in misc.h are
#include <iostream>
#include <cmath>
#include <fstream>
#include <cfloat>
#include <stdlib.h>
#include <string.h>
EDIT:
in misc.i generated by -E option,
extern "C++" char *basename (char *__filename)
throw () __asm ("basename") __attribute__ ((__nonnull__ (1)));
extern "C++" __const char *basename (__const char *__filename)
throw () __asm ("basename") __attribute__ ((__nonnull__ (1)));
# 640 "/usr/include/string.h" 3 4
# 1 "/usr/include/bits/string3.h" 1 3 4
# 23 "/usr/include/bits/string3.h" 3 4
extern void __warn_memset_zero_len (void) __attribute__((__warning__ ("memset used with constant zero length parameter; this could be due to transposed parameters")));
# 48 "/usr/include/bits/string3.h" 3 4
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__, __artificial__)) void *
memcpy (void *__restrict __dest, __const void *__restrict __src, size_t __len) throw ()
{
return __builtin___memcpy_chk (__dest, __src, __len, __builtin_object_size (__dest, 0));
}
...
# 641 "/usr/include/string.h" 2 3 4
...
You may be picking up the definition of basename() from libgen.h. On my OpenSUSE system, the version in libgen.h is defined with "throw ()" at the end (via the __THROW macro).
One thing you can try is to tell gcc to only run the preprocessor stage by adding the -E flag and then search for basename to see what is being defined:
g++ -pipe -W -Wall -fopenmp -ggdb3 -O2 -E -o misc.i ../../src/misc.cc
If that is happening, you'll either need to drop the include of libgen.h, match the throw specifier or change the name of your function.
" ../../src/misc.h:94: error: from previous declaration ‘char* basename(char*) throw ()’ "
I'm reading that as having been declared twice, once with throw() and once without.
Compiles for me, same flags.
g++ (Gentoo 4.3.4 p1.0, pie-10.1.5) 4.3.4
Your error says that there is a declaration of ‘char* basename(char*) throw ()’
try opening misc.h and searching for throw in the entire file, to see if you put the throw in yourself and just forgot about it.