To be honest, the calories listed on a Nutrition Facts label are an estimate rather than a strict value — but they are pretty darn close.
A calorie is quantified as the amount of energy required to raise the temperature of 1 milliliter of water by 1 degree Celsius. Scientists place a single, whole food in a calorimeter — a device with a combustion chamber, a thermometer and a container of water — and burn it. The rise in water temperature helps determine the approximate number of calories in that food.
Most manufacturers use existing databases (rather than conducting zillions of mini Bunsen burner bonfires) to determine the number of calories in each ingredient in a product, which they then add together to help determine their nutrition facts. To calculate the calories of your own recipes, check out calorieking.com or the U.S. Department of Agriculture’s food nutrient profile database — FoodData Central — for your (pretty accurate) totals.