Let's say I have an object.c
file, which defines a global variable MyObject
of type struct MyObjectStruct_s
which has a field char mydata[1024]
. While the MyObject
will end up as a (debug) in the final ELF/executable file - I cannot find MyObject.mydata
, and thus its address, in the debug info of the executable file.
So, I thought - could I somehow define an alias in the file where MyObject
is used (in the below example, the file is main.c
), which would function as a global variable and end up in the symbol table, but have the same address (and properies) as the field MyObject.mydata
? Here is an example:
CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
SET(CMAKE_INCLUDE_CURRENT_DIR ON)
project(my_project C CXX ASM)
add_executable(my_project
object.c
main.c
)
add_compile_options(
-Wall
)
set_target_properties(${PROJECT_NAME} PROPERTIES
OUTPUT_NAME "my_project"
SUFFIX ".exe"
)
# target_link_options(my_project ...)
# target_link_libraries(my_project ...)
object.h
#pragma once
#include <inttypes.h>
struct MyObjectStruct_s {
char mydata[1024];
};
typedef struct MyObjectStruct_s MyObjectStruct_t;
extern MyObjectStruct_t MyObject;
object.c
#include "object.h"
MyObjectStruct_t MyObject = {
.mydata = "Hello world!",
};
main.c
#include "object.h"
#include <stdio.h> // printf
// try add alias to extern struct field?
//extern char __attribute__ ((alias ("MyObject.mydata"))) var_alias[512];
// cannot: error: 'var_alias' aliased to undefined symbol 'MyObject.mydata'
void main(void) {
printf("%s\n", MyObject.mydata);
}
Build this with:
cmake ./ -DCMAKE_BUILD_TYPE=Debug -G "Unix Makefiles"
make
As you can see, I've tried to follow the example in https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attributes.html to have var_alias
be alias for MyObject.mydata
- however, I get an error "aliased to undefined symbol".
Also, just to confirm: can see MyObject
in the output of nm
for this executable, but no mention of mydata
there:
$ nm my_project.exe | grep 'MyObject\|mydata'
00000001400096e0 r .rdata$.refptr.MyObject
00000001400096e0 R .refptr.MyObject
0000000140008000 D MyObject
So, my question is: how can I instruct the gcc
build process (via CMake), to build the executable in such a way, so that I get a global symbol var_alias
to be an alias to the specific struct object field MyObject.mydata
-- and without changing the object.{c,h}
files?