Design Patterns for Shared Code
The goal of a shared code project is to have one repository that will be compiled and run for both Modeler and for the real platform. Depending on your needs, there might be additional targets as well: multiple real platforms, emulators, and so on. There are many ways to achieve this goal. The following sections describe two common ways.
Using Functions
In this approach, the main body of code makes function calls for platform-specific behavior. You implement a set of functions for each platform and link in the appropriate set as needed.
For example, you might be developing a protocol that needs to send hello packets. You have determined that this involves three steps that must be handled differently in the Riverbed model and on the real hardware. Your main code could look like this (with some code abstracted in comments):
double
calculate_next_tx_time (MyProtoState *state_ptr)
{
double curtime = platform_get_current_time ();
// some complicated algorithm to determine when to send next, based on local state
return complicated_val;
}
void
send_hello_pkt (MyProtoState *state_ptr)
{
unsigned char pkt_data [500];
// fill packet data with proper hello data
platform_send_packet (state_ptr, pkt_data);
double next_tx_time = calculate_next_tx_time ();
platform_schedule_next_hello (state_ptr, next_tx_time);
}
The three platform-specific steps are handled by the function calls to
platform_get_current_time ()platform_send_packet ()platform_schedule_next_hello ()
These functions will each exist in two versions, one for the model code and one for the real hardware.
Using #ifdefs
This approach puts all code together in one block and uses compiler #ifdefs to select the desired code at compile time. This is sometimes easier than function calls, such as when the program logic must change depending on platform or when you want to avoid a large number of “no-op” function calls.
The following example uses OPD_DES to identify Riverbed-specific code. The OPD_DES symbol is always defined in Riverbed code.
#ifdef OPD_DES
void
blocking_udp_client_main (blocking_udp_clientT_Svars *svars, const char *init_str);
#else
int main (int argc, char *argv [])
#endif
{
char *my_init;
#ifdef OPD_DES
my_init = init_str;
#else
my_init = argv [1];
#endif
.
.
}