Essentials of my problem: My project consists of both C and C++ files, some string constants (they are hardcoded in C part of project with #define
) are required to connect to computer via USB, but if I connect two or more of same type devices, they stop responding because those constants are same. Solution to this problem would be assigning those constants dynamically, from C++ files, so that variable from C++ code could reach C part, where those values are used.
What I have now: Values are defined in C headers as #define IDENTIFIER VALUE
(hardcoded), where both VALUE
is a C
primitive constant an int
like 0x1234
or char
array like "Some string"
. For instance:
#define IDENTIFIER1 0x1234
#define IDENTIFIER2 0x5678
#define IDENTIFIER3 "Some string"
#define IDENTIFIER4 "Another string"
I know that methods in C use those identifiers with other macros such as LOBYTE
and HIBYTE
, also values are passed to some functions.
I tried approaching this problem by replacing the string defines
with static cast char[]
variable definition wrapped in #ifndef
, but compiler noted that the identifiers are initializing non-const variables in some functions or is passed as a parameter.
I successfully compiled code in which i changed defining strings from #define IDENTIFIER VALUE
to static const unsigned char IDENTIFIER[] = VALUE;
, but I still need to define them in C++.
However I struggle to define hexadecimal numbers like 0x1234
. I've found other question including something related to my problem, so far I've tried to define hexadecimal values in following ways (found out that uint8_t is just a typedef of unsigned char, also found some questions about casting numbers to unsigned char
and some answers to questions about casting types):
static uint8_t IDENTIFIER[] = {0x12, 0x34, 0};
static const uint8_t IDENTIFIER[] = {0x12, 0x34, 0};
static const uint8_t IDENTIFIER[] = (uint8_t*)0x1234;
static const uint16_t identifier_int = 0x1234;
static const unsigned char IDENTIFIER[3] = identifier_int;
there is a function which uses IDENTIFIERs as arguments, its prototype looks like this:
void foo (uint8_t *bar, /*other arguments*/);
and later this is called like that:
foo(IDENTIFIER, /*other arguments*/)
What I want to achieve: Values should be defined in C++ code, where it should use some method to pass those values to C code.
Questions:
- What is best way to pass values from C++ code to C code? What alternatives there are?
Please inform me if I could increase clarity of my question!
Great thanks to @AhmedMasud for helping me out in defining my problem more clearly and giving few tips to clarify questions.