Using thermal expansion for mechanical work Assume I could heat up a bar with zero heat loss to the environment. I could then use the thermal expansion to do some work, for example compress a gas. Where does the energy needed for the compression come from, does the bar lose temperature while doing mechanical work?
 A: When you heat an object, thermal energy is flowing from the environment to the object.  It's the heat source that does the work.  You would be interested to read about the difference between internal energy, free energy, and especially enthalpy --- this last accounts for the work needed for thermal expansion and is generally what's used when computing phase change energies.
A: Zero is not correct. 'Negligible' is a better word. But even negligible means 'some'. That's where the energy comes from. It takes work to move heat from the environment into your object.
A: Consider the following thought experiment:
A horizontal metal rod is completely insulated thermally from the surroundings, and is not stretched/compressed by any external force.  An electric heater (inside the insulation) is turned on and delivers a precise amount of thermal energy to the rod.  The rod warms up to a final temperature, $T_1$, and expands to a final length $L_1$.  Since one end of the rod is fixed, the other end moves to accommodate the change in length to $L_1$
Now, repeat the experiment with an important difference.  A powerful compression spring, at its uncompressed length, is placed in contact with the free end of the rod;  the other end of the rod is still fixed, as is the far end of the compression spring.  The same amount of heat energy is delivered to the rod;  it expands and compresses the spring in the process. (The spring force also compresses the rod slightly.)
Next, the length of the compression spring is locked. (Did I mention that there is a ratchet mechanism on the spring that allows compression but not expansion?) 
Finally, the fixed end of the compression spring is released.  The compressed rod expands slightly, giving the spring a horizontal velocity.
Comparing the two experiments, the same energy has been delivered by the heater to both rods. The two rods end up with no external forces compressing them.  But in the second case, the spring contains both stored potential energy in its compressed state, and some kinetic energy.  This means that the rod has less heat energy in it.  
The second rod is slightly cooler than $T_1$, and thus slightly shorter than $L_1$.  The reduced energy of the rod is the source of the energy of the spring.
