Hi Ansis, first: you should use gcc-h...@gcc.gnu.org for questions like this...
On Thu, Nov 12, 2009 at 05:44:58AM -0800, ansis atteka wrote: > I have a struct in a header file. And I would like to have some of this > struct member fields to be constant, in case if this header file is included > from some particular Cpp files. Motivation for this is to avoid some silly > programmer errors by accidentally writing to this variable, when developer > is not supposed to do that. I guess that it is possible to catch these > errors already at the compile time with a const keyword. > > I already have approach, but I am not quite sure whether it is > safe(especially regarding the compiler optimizations). Below are uplaoded > files. > > In this case util.cpp is not allowed to edit S.y contents, while rw.cpp is > allowed to do that. File h.hpp contains the struct which is customized at > the preprocessor execution time by looking at the READONLY define. > > If this is not safe, are there any other approaches? I am afraid that > compiler might optimize out something. Assumption is that other threads will > not touch this member. > > Regards, > Ansis > > http://old.nabble.com/file/p26318895/Makefile Makefile > http://old.nabble.com/file/p26318895/rw.cpp rw.cpp > http://old.nabble.com/file/p26318895/h.hpp h.hpp > http://old.nabble.com/file/p26318895/util.cpp util.cpp > http://old.nabble.com/file/p26318895/util.hpp util.hpp > Yes, this approach is save. However, some minor remarks: - I'm not completely sure whether the position of "-DONLY_READ" is important for some versions of gcc ??? - it is safer, when you write it as argument before the first file: g++ -O3 -DONLY_READ -c util.cpp -o util.o - instead of using "-DONLY_READ" in the makefile it might be easier to use "#define ONLY_READ" inside the cpp-File - before including h.hpp: #define ONLY_READ #include "util.hpp" That creates exactly the same code. - The code might be easier to understand if you write: ONLY_READ int *y; instead of #ifdef ONLY_READ const int * y; #endif #ifndef ONLY_READ int * y; #endif inside h.hpp, and "#define ONLY_READ const" in all cpp-Files where you want it to be constant (util.cpp) and "#define ONLY_READ " in all cpp-Files, where you want read-access (rw.cpp). These defines have to be before the #include-Command. - if you use "ONLY_READ int *y;", you can also try #ifndef ONLY_READ #define ONLY_READ #endif ONLY_READ int *y; in the header-file h.hpp. This allows to include without "#define ONLY_READ": - if "ONLY_READ" is not defined, you get read-Access - if "ONLY_READ" is defined as "const", you have constant access. Axel