Heim Datenbank MySQL-Tutorial Accessing static Data and Functions in Legacy C

Accessing static Data and Functions in Legacy C

Jun 07, 2016 pm 03:44 PM
and data static

http://www.renaissancesoftware.net/blog/archives/450 It’s a new year; last year was a leap year; so the quadrennial reports of leap year bugs are coming in. Apologies are in the press from Apple, TomTom, and Microsoft. Trains we stopped f

http://www.renaissancesoftware.net/blog/archives/450

It’s a new year; last year was a leap year; so the quadrennial reports of leap year bugs are coming in. Apologies are in the press from Apple, TomTom, and Microsoft. Trains we stopped from running in China. Somehow calling them glitches seems to make it someone else’s fault, something out of their control. How long have leap years been around? Julius Caesar introduced Leap Years in the Roman empire over 2000 years ago. The Gregorian calendar has been around since 1682. This is not a new idea, or a new bug.

I’m going to try to take one excuse away from the programmers that create these bugs by answering a question that comes up all the time, “How do I test static functions in my C code?”

In code developed using TDD, static functions are tested indirectly through the public interface. As I mentioned in a this article TDD is a code rot radar. It helps you see design problems. Needing direct access to hidden functions and data in C is a sign of code rot. It is time to refactor.

But what about existing legacy code that has statics? It is probably way past the time for idealism and time for some pragmatism. In this article and the next, we’ll look at how to get your code untouched into the test harness and access those pesky <span>static </span>variables and functions.

If you don’t mind touching your code, you could change all mentions of static to STATIC. Then using the preprocessor, STATIC can he set to static during production and to nothing for test, making the names globally accessible. In gcc you would use these command line options

  • For production builds use -dSTATIC=static
  • For unit test builds use -dSTATIC

Let’s look at two options that, at least for access to statics, you will not have to touch your code to get it under test. First is <span>#include</span>-ing your .c in the test file. In the next article we’ll build a test adapter .c that give access to the hidden parts.

We are going to revisit code that is similar to the original code responsible for the Zune Bug. I rewrote the code to avoid attracting any lawyers but it is structured similarly to the original Zune driver, complete with static data and functions that must be correct for the function to work.

The header file provides a data structure and initialization function for figuring out the information about the date. Here is the header:

typedef struct Date
{
    int daysSince1980;
    int year;
    int dayOfYear;
    int month;
    int dayOfMonth;
    int dayOfWeek;
} Date;
 
void Date_Init(Date *, int daysSince1980);
 
enum {
    SUN = 0, MON, TUE, WED, THU, FRI, SAT
};
 
enum {
    JAN = 0, FEB, MAR, APR, MAY, JUN,
    JUL, AUG, SEP, OCT, NOV, DEC
};
Nach dem Login kopieren

Date_Init populates the Date instance passed in. Ignoring the fact that I can probably fully test this by rigging the daysSince1980, and inspecting the contents of the resultingDate structure, we are going to see how we can directly test the hidden functions and data.

Date_Init has three hidden helper functions.

void Date_Init(Date* date, int daysSince1980)
{
     date->daysSince1980 = daysSince1980;
     FirstSetYearAndDayOfYear(date);
     ThenSetMonthAndDayOfMonth(date);
     FinallySetDayOfWeek(date);
}
Nach dem Login kopieren

Date_Init is the tip of the iceberg. All the interesting stuff is happening in the hidden data and functions:

#include "Date.h"
#include 
 
enum
{
    STARTING_YEAR = 1980, STARTING_WEEKDAY = TUE
};
 
static const int nonLeapYearDaysPerMonth[12] =
{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
 
static const int leapYearDaysPerMonth[12] =
{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
 
static bool IsLeapYear(int year)
{
    if (year % 400 == 0)
        return true;
    if (year % 100 == 0)
        return false;
    if (year % 4 == 0)
        return true;
    return false;
}
 
static int GetDaysInYear(int year)
{
    if (IsLeapYear(year))
        return 366;
    else
        return 365;
}
 
static void FirstSetYearAndDayOfYear(Date * date)
{
    int days = date->daysSince1980;
    int year = STARTING_YEAR;
    int daysInYear = GetDaysInYear(year);
 
    while (days > daysInYear)
    {
        year++;
        days -= daysInYear;
        daysInYear = GetDaysInYear(year);
    }
 
    date->dayOfYear = days;
    date->year = year;
}
 
static void ThenSetMonthAndDayOfMonth(Date * date)
{
    int month = 0;
    int days = date->dayOfYear;
    const int * daysPerMonth = nonLeapYearDaysPerMonth;
    if (IsLeapYear(date->year))
        daysPerMonth = leapYearDaysPerMonth;
 
    while (days > daysPerMonth[month])
    {
        days -= daysPerMonth[month];
        month++;
    }
    date->month = month + 1;
    date->dayOfMonth = days;
}
 
static void FinallySetDayOfWeek(Date * date)
{
     date->dayOfWeek =((date->daysSince1980-1)+STARTING_WEEKDAY)%7;
}
 
void Date_Init(Date* date, int daysSince1980)
{
     date->daysSince1980 = daysSince1980;
     FirstSetYearAndDayOfYear(date);
     ThenSetMonthAndDayOfMonth(date);
     FinallySetDayOfWeek(date);
}
Nach dem Login kopieren

Let’s say you want to check the days per month vectors. You might want to write a test to check the months against the handy poem we use here in the US: Thirty days, has September, April, June and November; all the rest have thirty-one, except for February. It has 28 except in leap year it has 29.

If you started by writing this test…

TEST(Date, sept_has_30_days)
{
    LONGS_EQUAL(30, nonLeapYearDaysPerMonth[SEP]);
}
Nach dem Login kopieren

… you get this error:

DateTest.cpp:41: error: 'nonLeapYearDaysPerMonth' was not declared in this scope
Nach dem Login kopieren

Let’s get access to the hidden statics in the test case by including Date.c instead ofDate.h in DateTest.cpp. The full test case file looks like this now:

#include "CppUTest/TestHarness.h"
 
extern "C"
{
#include "Date.c"
}
 
TEST_GROUP(Date)
{
};
 
TEST(Date, sept_has_30_days)
{
    LONGS_EQUAL(30, nonLeapYearDaysPerMonth[SEP]);
}
Nach dem Login kopieren

With a little refactoring days per month vectors can be checked like this:

#include "CppUTest/TestHarness.h"
 
extern "C"
{
#include "Date.c"
}
 
TEST_GROUP(Date)
{
    const int * daysPerYearVector;
 
    void setup()
    {
        daysPerYearVector = nonLeapYearDaysPerMonth;
    }
 
    void itsLeapYear()
    {
        daysPerYearVector = leapYearDaysPerMonth;
    }
 
    void CheckNumberOfDaysPerMonth(int month, int days)
    {
        LONGS_EQUAL(days, daysPerYearVector[month]);
    }
 
    void ThirtyDaysHasSeptEtc()
    {
        CheckNumberOfDaysPerMonth(SEP, 30);
        CheckNumberOfDaysPerMonth(APR, 30);
        CheckNumberOfDaysPerMonth(JUN, 30);
        CheckNumberOfDaysPerMonth(NOV, 30);
 
        CheckNumberOfDaysPerMonth(OCT, 31);
        CheckNumberOfDaysPerMonth(DEC, 31);
        CheckNumberOfDaysPerMonth(JAN, 31);
        CheckNumberOfDaysPerMonth(MAR, 31);
        CheckNumberOfDaysPerMonth(MAY, 31);
        CheckNumberOfDaysPerMonth(JUL, 31);
        CheckNumberOfDaysPerMonth(AUG, 31);
    }
 
    void ExceptFebruaryHas(int days)
    {
      CheckNumberOfDaysPerMonth(FEB, days);
    }
};
 
TEST(Date, non_leap_year_day_per_month_table)
{
    ThirtyDaysHasSeptEtc();
    ExceptFebruaryHas(28);
}
 
TEST(Date, leap_year_day_per_month_table)
{
    itsLeapYear();
    ThirtyDaysHasSeptEtc();
    ExceptFebruaryHas(28);
}
Nach dem Login kopieren

You have access to all the hidden stuff, so you can write the test for the static functions:

IsLeapYear()GetDaysInYear()FirstSetYearAndDayOfYear(),ThenSetMonthAndDayOfMonth(), and FinallySetDayOfWeek().

If Date been an abstract data type, with its data structure hidden in the .c file, the tests would all have access to structure members hidden from the rest of the world.

There is a downside to this approach, which probably does not matter in this case, but could in others. You can only have one test file that can include a given .c file. In the next article we’ll solve that problem.

Have you heard of any interesting leap year bugs? Did you prevent your own?

Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn

Heiße KI -Werkzeuge

Undresser.AI Undress

Undresser.AI Undress

KI-gestützte App zum Erstellen realistischer Aktfotos

AI Clothes Remover

AI Clothes Remover

Online-KI-Tool zum Entfernen von Kleidung aus Fotos.

Undress AI Tool

Undress AI Tool

Ausziehbilder kostenlos

Clothoff.io

Clothoff.io

KI-Kleiderentferner

AI Hentai Generator

AI Hentai Generator

Erstellen Sie kostenlos Ai Hentai.

Heißer Artikel

R.E.P.O. Energiekristalle erklärten und was sie tun (gelber Kristall)
3 Wochen vor By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Beste grafische Einstellungen
3 Wochen vor By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. So reparieren Sie Audio, wenn Sie niemanden hören können
3 Wochen vor By 尊渡假赌尊渡假赌尊渡假赌

Heiße Werkzeuge

Notepad++7.3.1

Notepad++7.3.1

Einfach zu bedienender und kostenloser Code-Editor

SublimeText3 chinesische Version

SublimeText3 chinesische Version

Chinesische Version, sehr einfach zu bedienen

Senden Sie Studio 13.0.1

Senden Sie Studio 13.0.1

Leistungsstarke integrierte PHP-Entwicklungsumgebung

Dreamweaver CS6

Dreamweaver CS6

Visuelle Webentwicklungstools

SublimeText3 Mac-Version

SublimeText3 Mac-Version

Codebearbeitungssoftware auf Gottesniveau (SublimeText3)

Welche Funktion und Verwendung hat Static in der C-Sprache? Welche Funktion und Verwendung hat Static in der C-Sprache? Jan 31, 2024 pm 01:59 PM

Die Rolle und Verwendung von Statik in der C-Sprache: 1. Variablenbereich; Wenn das Schlüsselwort static vor einer Variablen steht, ist der Gültigkeitsbereich der Variablen auf die Datei beschränkt, in der sie deklariert ist. Mit anderen Worten, die Variable ist ein „Gültigkeitsbereich auf Dateiebene“, was sehr nützlich ist, um das „ zu verhindern. Problem der doppelten Definition von Variablen; 2. Lebenszyklus, statische Variablen werden einmal initialisiert, wenn die Ausführung des Programms beginnt, und zerstört, wenn das Programm endet usw.

So verwenden Sie „Static', „This', „Super' und „Final' in Java So verwenden Sie „Static', „This', „Super' und „Final' in Java Apr 18, 2023 pm 03:40 PM

1. static Bitte schauen Sie sich zuerst das folgende Programm an: publicclassHello{publicstaticvoidmain(String[]args){//(1)System.out.println("Hello, world!");//(2)}} Habe das gesehen Segmentprogramme sind den meisten Leuten bekannt, die Java studiert haben. Auch wenn Sie kein Java, aber andere Hochsprachen wie C gelernt haben, sollten Sie die Bedeutung dieses Codes verstehen können. Es gibt lediglich „Hallo Welt“ aus und hat keine andere Verwendung. Es zeigt jedoch den Hauptzweck des statischen Schlüsselworts.

Welche Daten befinden sich im Datenordner? Welche Daten befinden sich im Datenordner? May 05, 2023 pm 04:30 PM

Der Datenordner enthält System- und Programmdaten, wie z. B. Softwareeinstellungen und Installationspakete. Jeder Ordner im Datenordner stellt einen anderen Typ von Datenspeicherordner dar, unabhängig davon, ob sich die Datendatei auf den Dateinamen „Data“ oder die Dateierweiterung „Benannte Daten“ bezieht Es handelt sich bei allen um vom System oder Programm angepasste Datendateien. Daten sind eine Sicherungsdatei zur Datenspeicherung, die im Allgemeinen mit Meidaplayer, Notepad oder Word geöffnet werden kann.

Praktische Anwendungsszenarien und Verwendungsfähigkeiten des statischen Schlüsselworts in der C-Sprache Praktische Anwendungsszenarien und Verwendungsfähigkeiten des statischen Schlüsselworts in der C-Sprache Feb 21, 2024 pm 07:21 PM

Praktische Anwendungsszenarien und Verwendungsfähigkeiten des Schlüsselworts static in der C-Sprache 1. Übersicht static ist ein Schlüsselwort in der C-Sprache, das zum Ändern von Variablen und Funktionen verwendet wird. Seine Funktion besteht darin, seinen Lebenszyklus und seine Sichtbarkeit während der Programmausführung zu ändern und Variablen und Funktionen statisch zu machen. In diesem Artikel werden die tatsächlichen Anwendungsszenarien und Verwendungstechniken des statischen Schlüsselworts vorgestellt und anhand spezifischer Codebeispiele veranschaulicht. 2. Statische Variablen verlängern den Lebenszyklus von Variablen. Die Verwendung des Schlüsselworts static zum Ändern lokaler Variablen kann deren Lebenszyklus verlängern.

Die Rolle der Statik Die Rolle der Statik Jan 24, 2024 pm 04:08 PM

Die Funktionen von Static: 1. Methoden; 3. Andere Verwendungen; Optimierung des Speicherlayouts; 11. Vermeiden Sie wiederholte Initialisierung. 12. Verwendung in Funktionen. Detaillierte Einführung: 1. Variablen, statische Variablen. Wenn eine Variable als statisch deklariert wird, gehört sie zur Klassenebene und nicht zur Instanzebene. Dies bedeutet, dass unabhängig von der Anzahl der erstellten Objekte nur eine statische Variable und alle Objekte vorhanden sind Teilen Sie diese statischen Variablen usw.

Was tun, wenn die MySQL-Ladedaten verstümmelt sind? Was tun, wenn die MySQL-Ladedaten verstümmelt sind? Feb 16, 2023 am 10:37 AM

Die Lösung für die verstümmelten MySQL-Ladedaten: 1. Suchen Sie die SQL-Anweisung mit verstümmelten Zeichen. 2. Ändern Sie die Anweisung in „LOAD DATA LOCAL INFILE „employee.txt“ INTO TABLE EMPLOYEE Zeichensatz utf8;“.

So verwenden Sie die Java-Modifikatoren abstract, static und final So verwenden Sie die Java-Modifikatoren abstract, static und final Apr 26, 2023 am 09:46 AM

Modifikator abstract (abstract) 1. Abstract kann eine Klasse ändern (1) Die durch abstract geänderte Klasse wird als abstrakte Klasse bezeichnet (2) Syntax: abstractclass-Klassenname {} (3) Funktionen: Abstrakte Klassen können keine Objekte separat erstellen, sie können jedoch (4) Abstrakte Klassen können Mitgliedsvariablen und Mitgliedsmethoden definieren. Wenn sie zum Erstellen von Unterklassenobjekten verwendet werden, erstellt jvm standardmäßig ein übergeordnetes Klassenobjekt apply Wird angewendet, wenn JVM ein übergeordnetes Klassenobjekt erstellt. 2. Abstrakt kann Methoden ändern (1) Die durch asbtract geänderte Methode wird als abstrakte Methode bezeichnet (2) Syntax: Zugriffsmodifikator abstrakter Rückgabewert

So verwenden Sie den AND-Operator und den OR-Operator in einer SQL-Anweisung So verwenden Sie den AND-Operator und den OR-Operator in einer SQL-Anweisung May 28, 2023 pm 04:34 PM

SQLAND&OR-Operator Die AND- und OR-Operatoren werden zum Filtern von Datensätzen basierend auf mehr als einer Bedingung verwendet. AND und OR kombinieren zwei oder mehr Bedingungen in der WHERE-Unteranweisung. Der AND-Operator zeigt einen Datensatz an, wenn sowohl die erste als auch die zweite Bedingung wahr sind. Der ODER-Operator zeigt einen Datensatz an, wenn entweder die erste oder die zweite Bedingung wahr ist. Tabelle „Personen“: NachnameVornameAdresseStadtAdamsJohnOxfordStreetLondonBushGeorgeFifthAvenueNewYorkCarter

See all articles